Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Net
Imports System.Xml
Imports IMDBDLL
Imports System.Drawing.Imaging
Imports System.Drawing.ContentAlignment
Imports System.Threading
Imports System.Globalization
Imports System.Xml.Linq


Public Class Form1
#Region "Declare variables"
    Private createdImage As Bitmap
    Private createdCover As Bitmap
    Private bLoaded As Boolean = False
    Private currentDoc As XDocument
    Private sImgUrl As String = "http://images.themoviedb.org/backdrops/"
    Private sImgUrlPoster As String = "http://images.themoviedb.org/posters/"
    Private direcListBatch() As String
    Private Const API_KEY = "06c8358118c24c9308bb639c74c5b547"
    Private direcList() As String
    Dim aryBackdrops As New List(Of KeyValuePair(Of Bitmap, String))
    Dim aryPosters As New List(Of KeyValuePair(Of Bitmap, String))
    Dim resetEvents() As Threading.ManualResetEvent
    Dim resetEventsPoster() As Threading.ManualResetEvent
    Private currentTitle As IMDbTitle
    Private bNotFoundOnMovieDB As Boolean = False
    Private bNotFoundOnIMDB As Boolean = True
    Private sCurrentBatchMovie As String = ""
    Private bmpAudioFormat As Bitmap
    Private bmpAudioFormat2 As Bitmap
    Private bmpVideoResolution As Bitmap
    Private bmpFiletype As Bitmap
    Private bmpFiletype2 As Bitmap
    Private currentBatchDirec As String
    Private sDefaultTemplatePath As String = ""
    Private sActors As String = ""
    Private sGenres As String = ""
    Private sDirectors As String = ""
    Private bmpBatchBackdrop As Bitmap = Nothing
    Private iRetryCount As Integer = 0
    Dim bmpFanArt1, bmpFanArt2, bmpFanArt3 As Bitmap
    Dim iFanartCount As Integer = 0
    Dim loadedBitmap As Bitmap

#End Region
#Region "Declare IMDB methods"
    Public Delegate Sub functionCall(ByVal type As Integer, ByVal result As Object)
    Public Delegate Sub BatchFunctionCall(ByVal type As Integer, ByVal result As Object)
    ''' <summary>
    ''' Delegate to call the errorHandler.
    ''' </summary>
    ''' <param name="exc">The Exception.</param>
    Public Delegate Sub errorCall(ByVal exc As Exception)
    Public Delegate Sub BatchErrorCall(ByVal exc As Exception)

    ''' <summary>
    ''' Delegate to call the progressUpdater.
    ''' </summary>
    ''' <param name="value">Value to add to the progress bar.</param>
    Public Delegate Sub progressCall(ByVal value As Integer)
    Public Delegate Sub BatchProgressCall(ByVal value As Integer)

    ''' <summary>
    ''' Event of functionCall.
    ''' </summary>
    Private formFunctionCaller As functionCall
    Private formBatchFunctionCaller As BatchFunctionCall

    ''' <summary>
    ''' Event of errorCall.
    ''' </summary>
    Private formErrorCaller As errorCall
    Private formBatchErrorCaller As BatchErrorCall

    ''' <summary>
    ''' Event of progressCall.
    ''' </summary>
    Private formProgressCaller As progressCall
    Private formBatchProgressCaller As BatchProgressCall
    Private [error] = False
    Private imdbMgr As IMDbManager
    Private imdbBatchMgr As IMDbManager
#End Region

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try

        
            loadSettings()
            pbExistingSheet.Location = New Point(260, 4)
            'pbExistingSheet.Size = New Size(960, 540)
            pbExistingSheet.Size = New Size(640, 360)
            pbExistingSheet.Visible = False
            btnGenerate.Visible = True
            btnRedoWithTemplate.Visible = False
            btnRedo.Visible = False

            If Environment.GetCommandLineArgs.Length > 1 Then
                Dim retValue = Environment.GetCommandLineArgs
                Dim sMovieName = retValue(1)
                Dim sDirectory = retValue(2)
                'silent mode
                Me.Visible = False
                generateSilent(sDirectory, sMovieName)
                Application.Exit()
            Else

                If My.Settings.DefaultFolder <> vbNullString Then
                    txtManualFolderSelection.Text = My.Settings.DefaultFolder
                    populateMovieList()
                    txtBatchProcess.Text = My.Settings.DefaultFolder
                    populateMovieListBatch()
                    FileSystemWatcher1.Path = My.Settings.DefaultFolder
                End If
            End If
            formFunctionCaller = New functionCall(AddressOf processResult)
            formErrorCaller = (New errorCall(AddressOf ErrorHandler))
            formProgressCaller = (New progressCall(AddressOf progressUpdater))
            'set up events for batch mode
            formBatchFunctionCaller = New BatchFunctionCall(AddressOf BatchProcessResult)
            formBatchErrorCaller = (New BatchErrorCall(AddressOf BatchErrorHandler))
            formBatchProgressCaller = (New BatchProgressCall(AddressOf BatchProgressUpdater))
            loadSavedTemplates()
            lblVersion.Text = "Version " & System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()
            cboTemplates.DataSource = lstTemplates.Items
            cboTemplates.DisplayMember = "Text"
            cboApplyNewTemplate.DataSource = lstTemplates.Items
            cboApplyNewTemplate.DisplayMember = "Text"
            'pnlCreateSheet.Controls.Remove(pnlMovieInfo)
            'Me.Controls.Add(pnlMovieInfo)
            'pnlMovieInfo.Location = New Point(189, 495)
        Catch ex As Exception
            MessageBox.Show("Unable to locate you default folder.")
            txtManualFolderSelection.Text = ""
        End Try
    End Sub
#Region "IMDB Events"
    Sub progressUpdater(ByVal value As Integer)

    End Sub
    Sub ErrorHandler(ByVal exc As Exception)
        [error] = True
        If exc.Message = "No results found!" Then
            LogManual("Cannot find current movie on IMDB", 1)
            'check movie db.org and if present there get imdb id
            Dim s As KeyValuePair(Of String, String)
            s = lstMovies.SelectedItem
            Dim imdbID As String = ""
            imdbID = SearchOnTMDb_for_IMDbID(s.Value)
            If bNotFoundOnIMDB And bNotFoundOnMovieDB Then
                LogManual("Movie could not be found on IMDB or theMovieDB.org. Your out of luck mate.", 1)
            Else
                If imdbID <> "0" Then
                    LogManual("Movie found on TheMovieDB.org. Using IMDB ID to lookup movie info on IMDB", 1)
                    SearchOnIMDb(imdbID, 1)
                Else
                    bNotFoundOnIMDB = True
                    LogManual("No IMDB ID found for this movie. Using TheMovieDB.org to get information.", 1)
                    SearchOnTMDb_manual(s.Value)
                End If
            End If
        End If

    End Sub
    Sub processResult(ByVal type As Integer, ByVal result As Object)

        If [error] = False Then             'exact match so title is returned directly

            If type = 0 Then

                currentTitle = CType(result, IMDbTitle)
                ' LogManual("Found IMDB Match " & currentTitle.Title & " (" & currentTitle.Year & ")", 1)

                LogManual("Found IMDB ID: " & currentTitle.ID, 1)
                populateBackdropsIMDB(currentTitle.ID)
                populatePosters()
                populateMovieInfo()

            Else

                Dim listResults = CType(result, List(Of IMDbLink))

                If listResults.Count = 1 Then     'only one result so no point in showing multiple selection screen
                    imdbMgr.IMDbParse(listResults(0).URL)
                    'btnMoreFound.Visible = False

                Else

                    Dim list = CType(result, List(Of IMDbLink))

                    Results.getInstance.setResults(result)
                    'btnMoreFound.Visible = True

                    'btnMoreFound.Text = list.Count - 1 & " More Here..."

                    'imdbMgr.IMDbParse(list(0).URL)


                    '*** start test 17jul2012

                    If Results.getInstance.ShowDialog = Windows.Forms.DialogResult.OK Then
                        '*********bit of house keeping**********
                        bNotFoundOnIMDB = False
                        bNotFoundOnMovieDB = False
                        btnGenerate.Visible = True
                        btnRedoWithTemplate.Visible = False
                        txtManualLog.Text = ""
                        lstBackdrops.Items.Clear()
                        lstPoster.Items.Clear()
                        'lstPoster.DataSource = Nothing
                        pbBackdropPreview.Image = Nothing
                        pbPosterPreview.Image = Nothing
                        aryBackdrops.Clear()
                        aryPosters.Clear()
                        Application.DoEvents()
                        '**************************************
                        imdbMgr.IMDbParse(Results.getInstance.Selected)
                    End If

                    '*** end test 17jul2012

                End If

            End If

        End If

    End Sub

#End Region
#Region "Batch Events"
    Sub BatchProgressUpdater(ByVal value As Integer)
    End Sub
    Sub BatchErrorHandler(ByVal exc As Exception)
        [error] = True
        If exc.Message = "No results found!" Then
            Log("Cannot find current movie on IMDB")
            'check movie db.org and if present there get imdb id
            
            Dim imdbID As String = ""
            imdbID = SearchOnTMDb_for_IMDbID(sCurrentBatchMovie)
            If bNotFoundOnIMDB And bNotFoundOnMovieDB Then
                Log("Movie could not be found on IMDB or theMovieDB.org.Your out of luck mate.")
            Else
                If imdbID <> "0" Then
                    Log("Movie found on TheMovieDB.org. Using IMDB ID to lookup movie info on IMDB")
                    searchIMDBBatch(imdbID, 1)
                Else
                    bNotFoundOnIMDB = True
                    Log("No IMDB ID found for this movie. Using TheMovieDB.org to get information.")
                    SearchOnTMDb_manual(sCurrentBatchMovie)
                End If
            End If
        End If
        Application.DoEvents()
    End Sub
    Sub BatchProcessResult(ByVal type As Integer, ByVal result As Object)
        If [error] = False Then
            'exact match so title is returned directly
            If type = 0 Then
                currentTitle = CType(result, IMDbTitle)
                Log("Found IMDB ID " & currentTitle.ID)
                getMovieInfoIMDB(currentTitle)
            Else
                Dim listResults = CType(result, List(Of IMDbLink))
                imdbBatchMgr.IMDbParse(listResults(0).URL)
            End If
        End If
        Application.DoEvents()
    End Sub
#End Region

    Private Sub loadSettings()
        Try
            chkIncludeCover.Checked = My.Settings.IncludeCover
            chkIncludeRating.Checked = My.Settings.IncludeRating
            chkIncludeRuntime.Checked = My.Settings.IncludeRuntime
            chkIncludeSummary.Checked = My.Settings.IncludeSummary
            chkIncludeTitle.Checked = My.Settings.IncludeTitle
            txtMovieSheetName.Text = My.Settings.MovieSheetName
            txtCoverName.Text = My.Settings.CoverName
            txtCoverHeight.Text = My.Settings.CoverHeight.ToString
            txtCoverWidth.Text = My.Settings.CoverWidth.ToString
            txtDefaultBackdrop.Text = My.Settings.DefaultBackdrop
            If My.Settings.PrimarySource = "IMDB" Then
                optIMDB.Checked = True
            Else
                optMovieDB.Checked = True
            End If
            If My.Settings.AnalyseMKVs = True Then
                optEnabled.Checked = True
            Else
                optDisabled.Checked = True
            End If
            txt1080.Text = My.Settings.p1080
            txt720.Text = My.Settings.p720
            txtDolbyDigital.Text = My.Settings.DolbyPath
            txtDTS.Text = My.Settings.DTSPath
            txtDVDIcon.Text = My.Settings.DVDPath
            txtXvidIcon.Text = My.Settings.XvidPath
            txtDivxIcon.Text = My.Settings.DvixPath
            TxtDolbyStereo.Text = My.Settings.DolbyStereoPath
            txtMPEGaudio.Text = My.Settings.MPEGAudioPath
            txtMPEGvideo.Text = My.Settings.MPEGvideoPath
            txtH264Icon.Text = My.Settings.H264Path
            txtISOIcon.Text = My.Settings.ISOPath
            txtMKVIcon.Text = My.Settings.MKVPath
            txtAACIcon.Text = My.Settings.AACPath
            TxtAAC51icon.Text = My.Settings.AAC51Path
            txtBlueRayIcon.Text = My.Settings.BluRayPath
            TxtFLACicon.Text = My.Settings.FLACPath
            txtVorbisIcon.Text = My.Settings.VorbisPath
            chkUseOriginal.Checked = My.Settings.UseOriginal
            chkUseCache.Checked = My.Settings.UseCache
            chkExportCoverImage.Checked = My.Settings.ExportCover
            chkShowcase.Checked = My.Settings.Showcase
            'Set Language ComboBox
            If My.Settings.Language = Nothing Then
                comboLanguage.SelectedIndex = 0
            Else
                comboLanguage.SelectedIndex = My.Settings.Language
            End If

            If My.Settings.DefaultWDTV = True Then
                DefaultWDTV.Checked = True
            ElseIf My.Settings.Showcase = True Then
                chkShowcase.Checked = True
            ElseIf My.Settings.Msheet_t_b_s = True Then
                Msheet_T_b_s.Checked = True
            End If

            btnGo.Visible = True 'was False

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally

        End Try
    End Sub

    'TODO: Folder Name Parsing?
    Private Function generateImage(ByVal bmpCover As Bitmap, ByVal bmpBackdrop As Bitmap, ByVal sTitle As String, ByVal sSummary As String, ByVal sRuntime As String, ByVal sRating As String) As Bitmap
        '*** only used when 'use original' is checked
        Dim newbitmap As New Bitmap(1280, 720, Imaging.PixelFormat.Format32bppArgb)
        Dim g As Graphics
        Dim rectImage As New Rectangle(0, 0, 1280, 720)
        Dim rectCover As New Rectangle(50, 150, 240, 360)
        Dim rectVideo As New Rectangle(1162, 602, 113, 87)
        Dim rectAudio As New Rectangle(1044, 602, 113, 87)
        Dim rectAudio2 As New Rectangle(926, 602, 113, 87)
        Dim rectFiletype As New Rectangle(808, 602, 113, 87)
        Dim rectTitle As New Rectangle(0, 100, 1280, 100)
        ' Dim rectTitleFrame As New Rectangle(0, 5, 1280, 150)
        Dim rectSummary As New Rectangle(405, 205, 745, 400)
        ' Dim rectMainText As New Rectangle(400, 150, 750, 450)
        Dim rectMainText As New Rectangle(0, 50, 1280, 720)

        Dim fTitle As New Font("Ariel", 32, FontStyle.Regular, GraphicsUnit.Point)
        Dim fSynopsis As New Font("Ariel", 18, FontStyle.Regular, GraphicsUnit.Point)
        Dim fRunTime As New Font("Ariel", 15, FontStyle.Bold, GraphicsUnit.Point)
        Dim sfTitle = New StringFormat
        Dim sfSynopsis As New StringFormat

        Try
            sfSynopsis.Alignment = StringAlignment.Near
            sfSynopsis.LineAlignment = StringAlignment.Near
            sfTitle.Alignment = StringAlignment.Center
            sfTitle.LineAlignment = StringAlignment.Center
            g = Graphics.FromImage(newbitmap)
            g.Clear(Color.White)
            g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
            g.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAliasGridFit
            g.DrawImage(bmpBackdrop, rectImage)

            ' g.DrawImage(My.Resources.Images.TitleBG, rectTitleFrame)
            g.DrawImage(My.Resources.Images.shade, rectMainText)
            If My.Settings.IncludeCover Then
                g.DrawImage(bmpCover, rectCover)
            End If

            If My.Settings.IncludeTitle Then
                g.DrawString(sTitle, fTitle, Brushes.White, rectTitle, sfTitle)
            End If
            If My.Settings.IncludeSummary Then
                g.DrawString(sSummary, fSynopsis, Brushes.White, rectSummary, sfSynopsis)
            End If
            If My.Settings.IncludeRuntime Then
                g.DrawImage(My.Resources.Images.clock, 425, 450)
                g.DrawString(sRuntime, fRunTime, Brushes.White, 490, 475)
            End If
            If My.Settings.IncludeRating Then
                g.DrawImage(My.Resources.Images.favorite, 925, 450)
                g.DrawString(sRating, fRunTime, Brushes.White, 1000, 475)
            End If
            If bmpAudioFormat IsNot Nothing Then
                g.DrawImage(bmpAudioFormat, rectAudio)
            End If
            If bmpVideoResolution IsNot Nothing Then
                g.DrawImage(bmpVideoResolution, rectVideo)
            End If
            If bmpAudioFormat2 IsNot Nothing Then
                g.DrawImage(bmpAudioFormat2, rectAudio2)
            End If
            If bmpFiletype IsNot Nothing Then
                g.DrawImage(bmpFiletype, rectFiletype)
            End If
            createdImage = newbitmap
            createdCover = bmpCover


        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
        End Try
        Return newbitmap
    End Function
    Private Function SearchOnTMDb_manual(ByVal sMovieName As String) As Integer
        Dim httpReq As HttpWebRequest
        Dim httpResponse As HttpWebResponse
        Try
            Dim sStrippedTitle = stripMovieName(sMovieName)

            If sStrippedTitle <> "" Then
                sMovieName = sStrippedTitle
            End If

            Dim language As String
            language = getLanguageCode()
            LogManual("Searching TMDb for ..." & sStrippedTitle, 1)
            httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBSearchURL, language, API_KEY, sMovieName))
            httpResponse = httpReq.GetResponse

            Dim stream = httpResponse.GetResponseStream

            Dim doc As New XDocument
            Dim reader As New XmlTextReader(stream)

            doc = XDocument.Load(reader)

            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c
            Dim firstOBJ As Object = Nothing
            Dim bExactMatch As Boolean = False


            '*** BEGIN TEST ARRAY OF POSSIBLE HITS

            Dim array As New ArrayList

            For Each obj In q

                Dim Name_of_Movie = obj.Element("original_name").Value
                Dim TMDb_ID = obj.Element("id").Value

                Dim Lijst As New KeyValuePair(Of String, String)(TMDb_ID, Name_of_Movie)
                array.Add(Lijst)

            Next

            '*** END TEST ARRAY OF POSSIBLE HITS



            For Each obj In q

                If CStr(obj).IndexOf("Nothing found.") = -1 Then
                    ' firstOBJ = o


                    If LCase(obj.Element("name").Value).Equals(LCase(sMovieName)) Then
                        firstOBJ = obj
                        bExactMatch = True

                        Exit For

                    ElseIf firstOBJ Is Nothing Then  'exact match not found so use first one retuned(closest match)

                        firstOBJ = q(0)
                        bExactMatch = False

                    Else
                        LogManual("Movie Not Found. Let's try IMDB", 1)
                        bNotFoundOnMovieDB = True

                        If TabControl1.SelectedIndex = 1 Then     'we know user is in batch mode 

                            searchIMDBBatch(sMovieName, 0)

                        Else

                            SearchOnIMDb(sMovieName, 0)

                        End If

                    End If

                End If


            Next



            If firstOBJ IsNot Nothing Then
                'LogManual("Movie ID " & firstOBJ.Element("id").Value & " found. Exact Match=" & bExactMatch.ToString, 1)
                Return firstOBJ.Element("id").Value

            Else

                LogManual("Movie Not Found. Let's try IMDB", 1)
                bNotFoundOnMovieDB = True

                If TabControl1.SelectedIndex = 1 Then     'we know user is in batch mode 

                    searchIMDBBatch(sMovieName, 0)

                Else

                    SearchOnIMDb(sMovieName, 0)

                End If

                'Return 0

            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
        End Try
    End Function
    Private Function SearchOnTMDb_for_IMDbID(ByVal sMovieName As String) As String

        Dim httpReq As HttpWebRequest
        Dim httpResponse As HttpWebResponse

        Try
            Dim sStrippedTitle = stripMovieName(sMovieName)

            If sStrippedTitle <> "" Then

                sMovieName = sStrippedTitle

            End If

            Dim language As String
            language = getLanguageCode()

            'LogManual("Getting Movie " & sStrippedTitle, 1)

            httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBSearchURL, language, API_KEY, sMovieName))
            httpResponse = httpReq.GetResponse
            'LogManual("Requesting Search Response", 1)

            Dim stream = httpResponse.GetResponseStream
            'LogManual("Response Received", 1)

            Dim doc As New XDocument
            Dim reader As New XmlTextReader(stream)

            doc = XDocument.Load(reader)

            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c
            Dim firstOBJ As Object = Nothing
            Dim bExactMatch As Boolean = False

            For Each obj In q

                If CStr(obj).IndexOf("Nothing found.") = -1 Then
                    ' firstOBJ = o

                    If LCase(obj.Element("name").Value).Equals(LCase(sMovieName)) Then
                        firstOBJ = obj
                        bExactMatch = True
                        Exit For
                    End If

                    If firstOBJ Is Nothing Then
                        'exact match not found so use first one retuned(closest match)
                        firstOBJ = q(0)
                        bExactMatch = False
                    End If

                Else

                    Log("Movie Not Found")

                End If
            Next

            If firstOBJ IsNot Nothing Then
                'LogManual("Movie ID " & firstOBJ.Element("id").Value & " found. Exact Match=" & bExactMatch.ToString, 1)
                Return firstOBJ.Element("imdb_id").Value
            Else

                Return 0

            End If

        Catch ex As Exception

            MessageBox.Show(ex.Message)

        Finally

        End Try
    End Function
    Private Function getMovieInfo(ByVal id As Int16)
        Dim httpReq As HttpWebRequest
        Dim httpResponse As HttpWebResponse
        Try
            Dim language As String
            language = getLanguageCode()
            'httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBGetInfoUrl, API_KEY, id.ToString))
            httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBGetInfoUrl, language, API_KEY, id.ToString))
            'Log("Getting Movie Info")
            httpResponse = httpReq.GetResponse
            Dim stream = httpResponse.GetResponseStream
            'Log("Movie Info Received")
            Dim doc As New XDocument
            Dim reader As New XmlTextReader(stream)
            doc = XDocument.Load(reader)


            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c
            Dim firstOBJ = q.ElementAt(0)

            Dim sTitle As String = firstOBJ.Element("name").Value
            Dim sSummary As String = firstOBJ.Element("overview").Value
            Dim sRating As String = Math.Round(CDbl(firstOBJ.Element("rating").Value), 2).ToString
            Dim sRunTime As String = firstOBJ.Element("runtime").Value


            Dim q1 = From c1 In q.Elements("images").Elements("image") _
                   Where c1.Attribute("type") = "backdrop" _
                   Select c1
            Dim q2 = From c1 In q.Elements("images").Elements("image") _
                  Where c1.Attribute("type") = "poster" _
                  Select c1
            Log("Getting Backdrop")
            httpReq = WebRequest.Create(q1(0).Attribute("url").Value)
            httpResponse = httpReq.GetResponse
            Dim bmpBackdrop As New Bitmap(httpResponse.GetResponseStream)
            Log("Getting Poster")
            httpReq = WebRequest.Create(q2(0).Attribute("url").Value)
            httpResponse = httpReq.GetResponse
            Dim bmpCover As New Bitmap(httpResponse.GetResponseStream)
            Log("Generating Image")
            generateImage(bmpCover, bmpBackdrop, sTitle, sSummary, sRunTime, sRating)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Function

    Private Function ManuallyCreateVideoAudioFormat()
        If cmbVIDEOStream.Text = "720p" Then
            bmpVideoResolution = New Bitmap(My.Settings.p720)
        ElseIf cmbVIDEOStream.Text = "1080p" Then
            bmpVideoResolution = New Bitmap(My.Settings.p1080)
        ElseIf cmbVIDEOStream.Text = "MKV" Then
            bmpVideoResolution = New Bitmap(My.Settings.MKVPath)
        ElseIf cmbVIDEOStream.Text = "ISO" Then
            bmpVideoResolution = New Bitmap(My.Settings.DVDPath)
        ElseIf cmbVIDEOStream.Text = "XviD" Then
            bmpVideoResolution = New Bitmap(My.Settings.XvidPath)
        ElseIf cmbVIDEOStream.Text = "DivX" Then
            bmpVideoResolution = New Bitmap(My.Settings.DvixPath)
        ElseIf cmbVIDEOStream.Text = "MPEG-Video" Then
            bmpVideoResolution = New Bitmap(My.Settings.MPEGvideoPath)
        ElseIf cmbVIDEOStream.Text = "h264" Then
            bmpVideoResolution = New Bitmap(My.Settings.H264Path)
        ElseIf cmbVIDEOStream.Text = "Blu-Ray" Then
            bmpVideoResolution = New Bitmap(My.Settings.BluRayPath)
        ElseIf cmbVIDEOStream.Text = "DTS" Then
            bmpVideoResolution = New Bitmap(My.Settings.DTSPath)
        ElseIf cmbVIDEOStream.Text = "Dolby-Digital" Then
            bmpVideoResolution = New Bitmap(My.Settings.DolbyPath)
        ElseIf cmbVIDEOStream.Text = "Dolby-Stereo" Then
            bmpVideoResolution = New Bitmap(My.Settings.DolbyStereoPath)
        ElseIf cmbVIDEOStream.Text = "MP3" Then
            bmpVideoResolution = New Bitmap(My.Settings.MPEGAudioPath)
        ElseIf cmbVIDEOStream.Text = "AAC Stereo" Then
            bmpVideoResolution = New Bitmap(My.Settings.AACPath)
        ElseIf cmbVIDEOStream.Text = "AAC 5.1" Then
            bmpVideoResolution = New Bitmap(My.Settings.AAC51Path)
        Else
            bmpVideoResolution = Nothing
        End If

        If cmbAudioStream1.Text = "DTS" Then
            bmpAudioFormat = New Bitmap(My.Settings.DTSPath)
        ElseIf cmbAudioStream1.Text = "Dolby-Digital" Then
            bmpAudioFormat = New Bitmap(My.Settings.DolbyPath)
        ElseIf cmbAudioStream1.Text = "Dolby-Stereo" Then
            bmpAudioFormat = New Bitmap(My.Settings.DolbyStereoPath)
        ElseIf cmbAudioStream1.Text = "MP3" Then
            bmpAudioFormat = New Bitmap(My.Settings.MPEGAudioPath)
        ElseIf cmbAudioStream1.Text = "AAC Stereo" Then
            bmpAudioFormat = New Bitmap(My.Settings.AACPath)
        ElseIf cmbAudioStream1.Text = "AAC 5.1" Then
            bmpAudioFormat = New Bitmap(My.Settings.AAC51Path)
        ElseIf cmbAudioStream1.Text = "FLAC" Then
            bmpAudioFormat = New Bitmap(My.Settings.FLACPath)
        ElseIf cmbAudioStream1.Text = "OGG/Vorbis" Then
            bmpAudioFormat = New Bitmap(My.Settings.VorbisPath)
        Else
            bmpAudioFormat = Nothing
        End If

        If cmbAudioStream2.Text = "DTS" Then
            bmpAudioFormat2 = New Bitmap(My.Settings.DTSPath)
        ElseIf cmbAudioStream2.Text = "Dolby-Digital" Then
            bmpAudioFormat2 = New Bitmap(My.Settings.DolbyPath)
        ElseIf cmbAudioStream2.Text = "Dolby-Stereo" Then
            bmpAudioFormat2 = New Bitmap(My.Settings.DolbyStereoPath)
        ElseIf cmbAudioStream2.Text = "MP3" Then
            bmpAudioFormat2 = New Bitmap(My.Settings.MPEGAudioPath)
        ElseIf cmbAudioStream2.Text = "AAC Stereo" Then
            bmpAudioFormat2 = New Bitmap(My.Settings.AACPath)
        ElseIf cmbAudioStream2.Text = "AAC 5.1" Then
            bmpAudioFormat2 = New Bitmap(My.Settings.AAC51Path)
        ElseIf cmbAudioStream2.Text = "FLAC" Then
            bmpAudioFormat2 = New Bitmap(My.Settings.FLACPath)
        ElseIf cmbAudioStream2.Text = "OGG/Vorbis" Then
            bmpAudioFormat2 = New Bitmap(My.Settings.VorbisPath)
        Else
            bmpAudioFormat2 = Nothing
        End If

        'Convert Text lower Chars, some People use .iso instead .ISO
        If cmbFiletype.Text.ToLower = "mkv" Then
            If My.Settings.MKVPath <> "" Then
                bmpFiletype = New Bitmap(My.Settings.MKVPath)
            Else
                bmpFiletype = Nothing
            End If

        ElseIf cmbFiletype.Text.ToLower = "iso" Then
            bmpFiletype = New Bitmap(My.Settings.DVDPath)
            'ElseIf cmbFiletype.Text = "XviD" Then
            '   bmpFiletype = New Bitmap(My.Settings.XvidPath)
            'ElseIf cmbFiletype.Text = "DivX" Then
            '   bmpFiletype = New Bitmap(My.Settings.DvixPath)

        ElseIf cmbFiletype.Text = "Blu-Ray" Then
            If My.Settings.BluRayPath <> "" Then
                bmpFiletype = New Bitmap(My.Settings.BluRayPath)
            Else
                bmpFiletype = Nothing
            End If

        End If


    End Function

    'called when in batch mode
    Private Function getMovieInfoIMDB(ByVal title As IMDbTitle)
        Dim httpReq As HttpWebRequest
        Dim httpResponse As HttpWebResponse
        Dim language As String
        language = getLanguageCode()
        Try
            currentTitle = title
            'httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBIMDBLookup, API_KEY, title.ID))
            httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBIMDBLookup, language, API_KEY, title.ID))
            Log("Getting Movie Info")
            httpResponse = httpReq.GetResponse
            Dim stream = httpResponse.GetResponseStream
            Log("Movie Info Received")
            Dim doc As New XDocument
            Dim reader As New XmlTextReader(stream)
            doc = XDocument.Load(reader)

            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c

            Dim firstOBJ = q.ElementAt(0)
            If CStr(firstOBJ).IndexOf("Nothing found") <> -1 Then
                firstOBJ = Nothing
            End If
            If firstOBJ IsNot Nothing Then
                Dim iMovieDBId = firstOBJ.Element("id").Value
                'httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBGetInfoUrl, API_KEY, iMovieDBId))
                httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBGetInfoUrl, language, API_KEY, iMovieDBId))
                httpResponse = httpReq.GetResponse
                stream = httpResponse.GetResponseStream
                reader = New XmlTextReader(stream)
                doc = XDocument.Load(reader)
                currentDoc = doc
                q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                        Select c
                firstOBJ = q.ElementAt(0)
            End If

            txtTitle.Text = System.Web.HttpUtility.HtmlDecode(title.Title)
            'sometimes the imdb plot summarys have a trailing '|'. The following line removes it.
            txtSummary.Text = title.Plot.Replace("|", "")
            txtSummary.Text = System.Web.HttpUtility.HtmlDecode(txtSummary.Text)
            txtRating.Text = title.Rating
            txtRunTime.Text = title.Runtime

            txtCertification.Text = firstOBJ.Element("certification").Value
            txtOriginalTitle.Text = firstOBJ.Element("original_name").Value
            txtTagline.Text = firstOBJ.Element("tagline").Value

            Dim bmpBackdrop As Bitmap
            'Dim bmpCover As Bitmap
            Dim bSkipMovie As Boolean = False


            'use imdbInfo
            If currentTitle.Title <> vbNullString Then
                ' apostrophies come back wierd. this line boxes that off.
                currentTitle.Title = currentTitle.Title.Replace("&#x27;", "'")
                txtTitle.Text = System.Web.HttpUtility.HtmlDecode(currentTitle.Title)

                If txtTitle.Text.Contains("IMDb - ") Then
                    txtTitle.Text = txtTitle.Text.Replace("IMDb - ", "")
                End If

            ElseIf firstOBJ IsNot Nothing Then
                txtTitle.Text = System.Web.HttpUtility.HtmlDecode(firstOBJ.Element("name").Value)
            End If
            If currentTitle.Plot <> vbNullString Then
                txtSummary.Text = currentTitle.Plot.Replace("|", "")
            ElseIf firstOBJ IsNot Nothing Then
                txtSummary.Text = firstOBJ.Element("overview").Value
            End If
            If currentTitle.Rating <> vbNullString Then
                txtRating.Text = currentTitle.Rating & "/10"
            ElseIf firstOBJ IsNot Nothing Then
                'txtRating.Text = Math.Round(CDbl(firstOBJ.Element("rating").Value), 2).ToString
                txtRating.Text = firstOBJ.Element("rating").Value & "/10"

            End If
            If currentTitle.Runtime <> vbNullString Then
                txtRunTime.Text = currentTitle.Runtime
            ElseIf firstOBJ IsNot Nothing Then
                txtRunTime.Text = firstOBJ.Element("runtime").Value
            End If

            If currentTitle.Actors IsNot Nothing Then
                For Each actor In currentTitle.Actors
                    txtActors.Text = txtActors.Text & System.Web.HttpUtility.HtmlDecode(actor.Name) & ", "
                Next
                If txtActors.Text.EndsWith(", ") Then
                    txtActors.Text = txtActors.Text.Remove(txtActors.Text.Length - 2, 2)
                End If
            Else
                Dim qActor = From c1 In q.Elements("cast").Elements("person") _
                             Where c1.Attribute("job") = "Actor" _
                             Select c1
                For Each actor In qActor
                    txtActors.Text = txtActors.Text & System.Web.HttpUtility.HtmlDecode(actor.Attribute("name").Value) & ", "
                Next
                If txtDirectors.Text.EndsWith(", ") Then
                    txtDirectors.Text = txtDirectors.Text.Remove(txtDirectors.Text.Length - 2, 2)
                End If
            End If

            If currentTitle.Genres IsNot Nothing Then

                For Each genre In title.Genres
                    txtGenres.Text = txtGenres.Text & genre & ", "
                Next
            Else
                Dim q5 = From c1 In q.Elements("categories").Elements("category") _
             Where c1.Attribute("type") = "genre" _
             Select c1
                For Each genre In q5
                    txtGenres.Text = txtGenres.Text & genre.Attribute("name").Value & ", "
                Next

                If txtGenres.Text.EndsWith(", ") Then
                    txtGenres.Text = txtGenres.Text.Remove(txtGenres.Text.Length - 2, 2)
                End If
                'genre support in MovieDB.org getInfo call?

            End If

            If currentTitle.Directors IsNot Nothing Then
                For Each director In currentTitle.Directors
                    txtDirectors.Text = txtDirectors.Text & director.Name & ", "
                Next
            Else
                Dim qDirector = From c1 In q.Elements("cast").Elements("person") _
             Where c1.Attribute("job") = "Director" _
             Select c1
                For Each director In qDirector
                    txtDirectors.Text = txtDirectors.Text & director.Attribute("name").Value & ", "
                Next
            End If
            txtDirectors.Text = System.Web.HttpUtility.HtmlDecode(txtDirectors.Text)
            If txtDirectors.Text.EndsWith(", ") Then
                txtDirectors.Text = txtDirectors.Text.Remove(txtDirectors.Text.Length - 2, 2)
            End If

            If currentTitle.Year <> vbNullString Then
                txtYear.Text = currentTitle.Year
            Else
                txtYear.Text = Mid(firstOBJ.Element("released").Value, 1, 4)
            End If

            Dim q4 = From c1 In q.Elements("countries").Elements("country")
            For Each country In q4
                txtCountries.Text = txtCountries.Text & country.Attribute("name").Value & ", "
            Next
            If txtCountries.Text.EndsWith(", ") Then
                txtCountries.Text = txtCountries.Text.Remove(txtCountries.Text.Length - 2, 2)
            End If

            Dim q6 = From c1 In q.Elements("studios").Elements("studio")
            For Each studio In q6
                txtStudios.Text = txtStudios.Text & studio.Attribute("name").Value & ", "
            Next

            If txtStudios.Text.EndsWith(", ") Then
                txtStudios.Text = txtStudios.Text.Remove(txtStudios.Text.Length - 2, 2)
            End If


            '=== START BACKDROP PROCESSING IN BATCH MODE ===

            Dim q1 = From c1 In q.Elements("images").Elements("image") _
                   Where c1.Attribute("type") = "backdrop" _
                   Select c1

            If q1.Count = 0 Then 'there are no backdrops available for this movie

                If My.Settings.DefaultBackdrop <> vbNullString Then
                    bmpBackdrop = New Bitmap(My.Settings.DefaultBackdrop)
                    Log("No Backdrops available from theMovieDB.org, so using your default backdrop.")
                Else
                    Log("No Backdrops available from theMovieDB.org and you have not selected a default backdrop.")

                End If

            Else 'so there are backdrops available

                Dim q11 = From c1 In q.Elements("images").Elements("image") _
                       Where c1.Attribute("type") = "backdrop" And c1.Attribute("size") = "original" _
                       Select c1

                Dim q12 = From c1 In q.Elements("images").Elements("image") _
                   Where c1.Attribute("type") = "backdrop" And c1.Attribute("size") = "w1280" _
                   Select c1

                Dim q13 = From c1 In q.Elements("images").Elements("image") _
                   Where c1.Attribute("type") = "backdrop" And c1.Attribute("size") = "poster" _
                   Select c1

                Dim q14 = From c1 In q.Elements("images").Elements("image") _
                   Where c1.Attribute("type") = "backdrop" And c1.Attribute("size") = "thumb" _
                   Select c1


                If q11.Count > 0 Then

                    httpReq = WebRequest.Create(q11(0).Attribute("url").Value)
                    

                ElseIf q12.Count > 0 Then

                    httpReq = WebRequest.Create(q12(0).Attribute("url").Value)

                ElseIf q13.Count > 0 Then

                    httpReq = WebRequest.Create(q13(0).Attribute("url").Value)

                Else

                    httpReq = WebRequest.Create(q14(0).Attribute("url").Value)

                End If

                Log("Getting Backdrop")
                httpResponse = httpReq.GetResponse
                bmpBackdrop = New Bitmap(httpResponse.GetResponseStream)

            End If

            '=== END BACKDROP PROCESSING IN BATCH MODE ===



            '=== START POSTER PROCESSING IN BATCH MODE ===

            Dim q2 = From c1 In q.Elements("images").Elements("image") _
                  Where c1.Attribute("type") = "poster" _
                  Select c1

            Dim q21 = From c1 In q.Elements("images").Elements("image") _
                Where c1.Attribute("type") = "poster" And c1.Attribute("size") = "original" _
                Select c1

            Dim q22 = From c1 In q.Elements("images").Elements("image") _
                  Where c1.Attribute("type") = "poster" And c1.Attribute("size") = "mid" _
                  Select c1

            Dim q23 = From c1 In q.Elements("images").Elements("image") _
                  Where c1.Attribute("type") = "poster" And c1.Attribute("size") = "w342" _
                  Select c1

            Dim q24 = From c1 In q.Elements("images").Elements("image") _
                  Where c1.Attribute("type") = "poster" And c1.Attribute("size") = "cover" _
                  Select c1

            Dim q25 = From c1 In q.Elements("images").Elements("image") _
                  Where c1.Attribute("type") = "poster" And c1.Attribute("size") = "w154" _
                  Select c1

            Dim q26 = From c1 In q.Elements("images").Elements("image") _
                  Where c1.Attribute("type") = "poster" And c1.Attribute("size") = "thumb" _
                  Select c1


            If q2.Count = 0 Then 'there are no Posters available

                If title.CoverURL <> vbNullString Then
                    Log("No Poster available on theMovieDB.org for this movie. Attempting to get IMDB Poster")

                    httpReq = WebRequest.Create(title.CoverURL)
                    httpResponse = httpReq.GetResponse
                    createdCover = New Bitmap(httpResponse.GetResponseStream)

                Else
                    Log("No Posters available on either IMDB or theMovieDB.org. Skipping Movie")
                    bSkipMovie = True

                End If

            ElseIf q21.Count > 0 Then
                httpReq = WebRequest.Create(q21(0).Attribute("url").Value)
            ElseIf q22.Count > 0 Then
                httpReq = WebRequest.Create(q22(0).Attribute("url").Value)
            ElseIf q23.Count > 0 Then
                httpReq = WebRequest.Create(q23(0).Attribute("url").Value)
            ElseIf q24.Count > 0 Then
                httpReq = WebRequest.Create(q24(0).Attribute("url").Value)
            ElseIf q25.Count > 0 Then
                httpReq = WebRequest.Create(q25(0).Attribute("url").Value)
            Else
                httpReq = WebRequest.Create(q26(0).Attribute("url").Value)
            End If

            If q2.Count > 0 Then

                Log("Getting Poster")
                httpResponse = httpReq.GetResponse
                createdCover = New Bitmap(httpResponse.GetResponseStream)

            End If

            '=== END POSTER PROCESSING IN BATCH MODE ===


            If iFanartCount > 0 Then

                Dim qFanArt = From c1 In q.Elements("images").Elements("image") _
                       Where c1.Attribute("type") = "backdrop" _
                       And c1.Attribute("size") = "original" _
                       And c1.Attribute("url").Value.Replace("_original", "") <> q1(0).Attribute("url").Value _
                       Select c1

                For i As Integer = 0 To iFanartCount Step 1

                    If qFanArt.Count > i And i <= 2 Then
                        Log("Getting Fanart " & (i + 1).ToString)
                        httpReq = WebRequest.Create(qFanArt(i).Attribute("url").Value)
                        httpResponse = httpReq.GetResponse

                        Select Case i
                            Case 0
                                bmpFanArt1 = New Bitmap(httpResponse.GetResponseStream)
                            Case 1
                                bmpFanArt2 = New Bitmap(httpResponse.GetResponseStream)
                            Case 2
                                bmpFanArt3 = New Bitmap(httpResponse.GetResponseStream)
                        End Select

                    End If

                Next
            End If



            If bSkipMovie = False Then
                If My.Settings.AnalyseMKVs And cbManuallyInput.Checked = False Then
                    'get MKV file name
                    Dim direcInfo As New IO.DirectoryInfo(currentBatchDirec)
                    Dim targetFile As String = ""
                    Dim fileAry As New List(Of IO.FileInfo)
                    fileAry.AddRange(direcInfo.GetFiles("*.MKV"))
                    fileAry.AddRange(direcInfo.GetFiles("*.mkv"))
                    fileAry.AddRange(direcInfo.GetFiles("*.AVI"))
                    fileAry.AddRange(direcInfo.GetFiles("*.avi"))
                    'fileAry.AddRange(direcInfo.GetFiles("*.ISO"))
                    'fileAry.AddRange(direcInfo.GetFiles("*.iso"))
                    fileAry.AddRange(direcInfo.GetFiles("*.VOB"))
                    fileAry.AddRange(direcInfo.GetFiles("*.vob"))
                    fileAry.AddRange(direcInfo.GetFiles("*.DIVX"))
                    fileAry.AddRange(direcInfo.GetFiles("*.divx"))
                    fileAry.AddRange(direcInfo.GetFiles("*.M2TS"))
                    fileAry.AddRange(direcInfo.GetFiles("*.m2ts"))
                    fileAry.AddRange(direcInfo.GetFiles("vts*.ifo"))
                    fileAry.AddRange(direcInfo.GetFiles("*.mp4"))
                    fileAry.AddRange(direcInfo.GetFiles("*.MP4"))
                    Dim maxSize As Long = 0
                    For Each f In fileAry
                        If f.Length > maxSize Then
                            targetFile = f.FullName
                        End If
                    Next
                    If targetFile <> vbNullString Then
                        getVideoInfo(targetFile)
                    End If
                Else
                    ManuallyCreateVideoAudioFormat()
                End If
                Log("Generating Image")
                bmpBatchBackdrop = bmpBackdrop
                If chkUseOriginal.Checked = False Then
                    createdImage = ApplyTemplate(sDefaultTemplatePath, bmpBackdrop, createdCover)
                Else
                    createdImage = generateImage(createdCover, bmpBackdrop, txtTitle.Text, txtSummary.Text, txtRunTime.Text, txtRating.Text)
                End If
            End If
            'successfull so reset retry counter.
            iRetryCount = 0
        Catch wex As Net.WebException
            If iRetryCount <= 10 Then
                iRetryCount += 1
                Log(wex.Message & vbCrLf & "Retrying " & iRetryCount.ToString & " of 10.")
                getMovieInfoIMDB(title)
            Else
                Log(wex.Message & vbCrLf & " I have tried 10 times to get this movie and it isnt happening. Sorry :(")
                iRetryCount = 0
            End If
        Catch ex As Exception
            Log(ex.Message)
        End Try
    End Function
    Private Function stripMovieName(ByVal sMovieName As String) As String
        Dim sStrippedTitle As String = ""
        Dim iStartIndex As Integer = 0
        Dim iEndIndex As Integer = 0
        Dim iLength As Integer = 0
        Dim mLenght As Integer = sMovieName.Length.ToString

        Try
            Dim a, b, c As Integer

            For a = 0 To mLenght
                iStartIndex = sMovieName.IndexOf("(")

                If iStartIndex <> -1 Then
                    iEndIndex = sMovieName.IndexOf(")")
                    iLength = iEndIndex - iStartIndex
                    sStrippedTitle = Trim(sMovieName.Remove(iStartIndex, iLength + 1))
                    sStrippedTitle = sStrippedTitle.ToLower
                    sMovieName = sStrippedTitle
                Else
                    a = mLenght
                End If
            Next

            For b = 0 To mLenght
                iStartIndex = sMovieName.IndexOf("[")

                If iStartIndex <> -1 Then
                    iEndIndex = sMovieName.IndexOf("]")
                    iLength = iEndIndex - iStartIndex
                    sStrippedTitle = Trim(sMovieName.Remove(iStartIndex, iLength + 1))
                    sStrippedTitle = sStrippedTitle.ToLower
                    sMovieName = sStrippedTitle
                Else
                    b = mLenght
                End If
            Next

            For c = 0 To mLenght
                iStartIndex = sMovieName.IndexOf("{")

                If iStartIndex <> -1 Then
                    iEndIndex = sMovieName.IndexOf("}")
                    iLength = iEndIndex - iStartIndex
                    sStrippedTitle = Trim(sMovieName.Remove(iStartIndex, iLength + 1))
                    sStrippedTitle = sStrippedTitle.ToLower
                    sMovieName = sStrippedTitle
                Else
                    c = mLenght
                End If
            Next

            If sStrippedTitle.Contains("divx") = True Then
                sStrippedTitle = sStrippedTitle.Replace("divx", "")
            End If

            If sStrippedTitle.Contains("dvdrip") = True Then
                sStrippedTitle = sStrippedTitle.Replace("dvdrip", "")
            End If

            If sStrippedTitle.Contains("720p") = True Then
                sStrippedTitle = sStrippedTitle.Replace("720p", "")
            End If

            If sStrippedTitle.Contains("1080p") = True Then
                sStrippedTitle = sStrippedTitle.Replace("1080p", "")
            End If

            If sStrippedTitle.Contains("-") = True Then
                sStrippedTitle = sStrippedTitle.Replace("-", " ")
            End If

            If sStrippedTitle.Contains(".") = True Then
                sStrippedTitle = sStrippedTitle.Replace(".", " ")
            End If

            sStrippedTitle = Trim(sStrippedTitle)

            If sStrippedTitle <> "" Then
                Return sStrippedTitle
            Else
                sStrippedTitle = sMovieName
                Return sStrippedTitle
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Function
    Private Sub Log(ByVal sMsg As String)
        Try
            txtStatus.AppendText(sMsg & vbCrLf)
            Application.DoEvents()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub


    Private Sub btnProcess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProcess.Click
        'now enum thru the folder getting movie info for each one and placing folder & wd_tv jpgs in the folders

        lblStatus.Text = ""
        Dim bFreshDownload = False
        iFanartCount = 0

        Try
            Cursor.Current = Cursors.WaitCursor
            If txtBatchProcess.Text <> vbNullString Then
                Dim directoryList As String() ' array for directories
                directoryList = direcListBatch
                'check for number of fanart images in loaded template
                Dim doc As New XDocument
                Dim fs As New IO.FileStream(sDefaultTemplatePath, IO.FileMode.Open)
                Dim reader As New XmlTextReader(fs)
                doc = XDocument.Load(reader)
                Dim imageElements = From c In doc.Elements("Template").Elements("ImageDrawTemplate").Elements("Elements").Elements("ImageElement") _
                             Select c

                fs.Close()

                For Each img In imageElements

                    If img.Attribute("SourceData").Value.IndexOf("fanart.tvixie") <> -1 _
                    Or img.Attribute("SourceData").Value.IndexOf("thumb1.tvixie") <> -1 _
                    Or img.Attribute("SourceData").Value.IndexOf("thumb2.tvixie") <> -1 _
                    Or img.Attribute("SourceData").Value.IndexOf("%FANART1%") <> -1 _
                    Or img.Attribute("SourceData").Value.IndexOf("%FANART2%") <> -1 _
                    Or img.Attribute("SourceData").Value.IndexOf("%FANART3%") <> -1 Then
                        iFanartCount += 1
                    End If
                Next

                Log("The default template uses " & iFanartCount.ToString & " fanart\thumb image(s).")
                Dim iCount As Integer = 1
                For Each direc In directoryList
                    'House keeping*********
                    clearFanArt()
                    bNotFoundOnIMDB = False
                    bNotFoundOnMovieDB = False
                    createdCover = Nothing
                    createdImage = Nothing
                    bFreshDownload = False
                    bmpVideoResolution = Nothing
                    bmpAudioFormat2 = Nothing
                    bmpAudioFormat = Nothing
                    bmpFiletype = Nothing
                    bmpFiletype2 = Nothing

                    My.Settings.VideoFormatName = ""
                    My.Settings.MediaFormatName = ""
                    My.Settings.SoundFormatName = ""
                    My.Settings.SoundFormat2Name = ""
                    My.Settings.ResolutionName = ""

                    clearMovieInfo()
                    '***********************
                    lblStatus.Text = "Processing " & iCount.ToString & " of " & directoryList.Length.ToString & " movies."
                    Application.DoEvents()
                    Dim movieName = direc.Remove(0, txtBatchProcess.Text.Count + 1)
                    sCurrentBatchMovie = movieName
                    currentBatchDirec = direc
                    If IO.File.Exists(direc & "\Movie_Info.xml") And My.Settings.UseCache Then
                        LoadXML(direc & "\Movie_Info.xml")
                        createdCover = New Bitmap(direc & "\cover.jpg")
                        If iFanartCount > 0 Then
                            If IO.File.Exists(direc & "\fanart1.jpg") Then
                                bmpFanArt1 = New Bitmap(direc & "\fanart1.jpg")
                            End If
                            If IO.File.Exists(direc & "\fanart2.jpg") Then
                                bmpFanArt2 = New Bitmap(direc & "\fanart2.jpg")
                            End If
                            If IO.File.Exists(direc & "\fanart3.jpg") Then
                                bmpFanArt3 = New Bitmap(direc & "\fanart3.jpg")
                            End If
                        End If
                        If My.Settings.AnalyseMKVs And cbManuallyInput.Checked = False Then
                            'get MKV file name
                            Dim direcInfo As New IO.DirectoryInfo(currentBatchDirec)
                            Dim targetFile As String = ""

                            Dim fileAry As New List(Of IO.FileInfo)
                            fileAry.AddRange(direcInfo.GetFiles("*.mkv"))
                            fileAry.AddRange(direcInfo.GetFiles("*.divx"))
                            fileAry.AddRange(direcInfo.GetFiles("*.avi"))
                            'fileAry.AddRange(direcInfo.GetFiles("*.iso"))
                            fileAry.AddRange(direcInfo.GetFiles("*.vob"))
                            fileAry.AddRange(direcInfo.GetFiles("*.m2ts"))
                            fileAry.AddRange(direcInfo.GetFiles("vts*.ifo"))
                            fileAry.AddRange(direcInfo.GetFiles("*.mp4"))

                            Dim maxSize As Long = 0
                            For Each f In fileAry
                                If f.Length > maxSize Then
                                    targetFile = f.FullName
                                End If
                            Next
                            If targetFile <> vbNullString Then
                                getVideoInfo(targetFile)
                            End If
                        End If
                        createdImage = ApplyTemplate(sDefaultTemplatePath, New Bitmap(direc & "\backdrop.jpg"), createdCover)
                        bFreshDownload = False

                    Else
                        searchIMDBBatch(movieName, 0)
                        bFreshDownload = True
                    End If


                    If createdCover IsNot Nothing Then
                        If My.Settings.ExportCover Then
                            Dim bmpFolderImage As New Bitmap(My.Settings.CoverWidth, My.Settings.CoverHeight)

                            Dim g = Graphics.FromImage(bmpFolderImage)
                            Dim coverRect As New Rectangle(0, 0, My.Settings.CoverWidth, My.Settings.CoverHeight)

                            g.DrawImage(createdCover, coverRect)
                            bmpFolderImage.Save(direc & "\" & My.Settings.CoverName, Imaging.ImageFormat.Jpeg)
                        End If
                    End If

                    If createdImage IsNot Nothing Then

                        If My.Settings.UseCache And bFreshDownload Then

                            GenerateXML(direc)
                            bmpBatchBackdrop.Save(direc & "\backdrop.jpg", Imaging.ImageFormat.Jpeg)
                            createdCover.Save(direc & "\cover.jpg", Imaging.ImageFormat.Jpeg)
                            If bmpFanArt1 IsNot Nothing Then
                                bmpFanArt1.Save(direc & "\fanart1.jpg")
                            End If
                            If bmpFanArt2 IsNot Nothing Then
                                bmpFanArt2.Save(direc & "\fanart2.jpg")
                            End If
                            If bmpFanArt3 IsNot Nothing Then
                                bmpFanArt3.Save(direc & "\fanart3.jpg")
                            End If
                        End If

                        '**Something sometimes creates GDI+ error with following line
                        createdImage.Save(direc & "\" & My.Settings.MovieSheetName, Imaging.ImageFormat.Jpeg)

                        'populate previewbox
                        pbGeneratedImage.ImageLocation = direc & "\" & My.Settings.MovieSheetName
                        pbGeneratedImage.SizeMode = PictureBoxSizeMode.Zoom
                        Application.DoEvents()

                        If chkShowcase.Checked Then

                            Dim newsheet As New Bitmap(1280, 720, Imaging.PixelFormat.Format32bppArgb)
                            Dim b = Graphics.FromImage(newsheet)
                            Dim hdBackdrop = bmpBatchBackdrop

                            '**** backdrop resizing, cropping & renaming start ****
                            b.InterpolationMode = InterpolationMode.High
                            b.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
                            b.DrawImage(hdBackdrop, 0, 0, 1280, 720)
                            newsheet.SetResolution(1280, 720)

                            '**** cropping starts here
                            Dim CroppedImage As New Bitmap(1280, 459)
                            Dim h = Graphics.FromImage(CroppedImage)
                            h.DrawImage(newsheet, New Rectangle(0, 0, CroppedImage.Width, CroppedImage.Height), 0, 0, CroppedImage.Width, CroppedImage.Height, GraphicsUnit.Pixel)
                            h.DrawImage(My.Resources.Images.diffuse, New Rectangle(0, CroppedImage.Height - My.Resources.Images.diffuse.Height, 1280, 459), 0, 0, 1280, 459, GraphicsUnit.Pixel)
                            h.Dispose()
                            CroppedImage.Save(currentBatchDirec & "_sheet.jpg", Imaging.ImageFormat.Jpeg)
                            '**** backdrop resizing, cropping & renaming end ****
                            Log("Showcase backdrop generated successfully...")
                        End If

                        If Msheet_T_b_s.Checked Then
                            Dim newsheet As New Bitmap(1280, 720, Imaging.PixelFormat.Format32bppArgb)
                            Dim b = Graphics.FromImage(newsheet)
                            Dim hdBackdrop = bmpBatchBackdrop
                            b.InterpolationMode = InterpolationMode.High
                            b.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
                            b.DrawImage(hdBackdrop, 0, 0, 1280, 720)
                            newsheet.SetResolution(1280, 720)
                            Dim h = Graphics.FromImage(hdBackdrop)
                            h.DrawImage(hdBackdrop, New Rectangle(0, 0, newsheet.Width, newsheet.Height), 0, 0, newsheet.Width, newsheet.Height, GraphicsUnit.Pixel)
                            newsheet.Save(currentBatchDirec & "_sheet.jpg", Imaging.ImageFormat.Jpeg)
                            Log(currentBatchDirec & "_sheet generated successfully...")
                        End If

                    End If
                    'End If

                    iCount += 1
                Next

                Log("--------")
                Log("All done")
                Log("--------")

            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)

        Finally
            Cursor.Current = Cursors.Default
        End Try

    End Sub

    Private Sub txtManualFolderSelection_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtManualFolderSelection.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf FolderBrowserDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()
        'thFolderSelection.
        ' If FolderBrowserDialog1.ShowDialog(Me) = 1 Then
        If FolderBrowserDialog1.SelectedPath <> vbNullString Then
            txtManualFolderSelection.Text = FolderBrowserDialog1.SelectedPath
            populateMovieList()
            My.Settings.DefaultFolder = txtManualFolderSelection.Text
            My.Settings.Save()
            FileSystemWatcher1.Path = My.Settings.DefaultFolder
        End If
        ' End If
    End Sub
    Private Sub populateMovieList()
        lstMovies.SelectionMode = SelectionMode.None
        Dim directoryList As String() ' array for directories
        If chkUnprocessedOnlyManual.Checked Then
            directoryList = hideProcessedFolders(IO.Directory.GetDirectories(txtManualFolderSelection.Text))
        Else
            directoryList = IO.Directory.GetDirectories(txtManualFolderSelection.Text)
        End If
        direcList = directoryList
        Dim movieArray As New ArrayList
        Dim mvAry As New List(Of KeyValuePair(Of String, String))

        For Each direc In directoryList

            'Dim movieName = direc.Remove(0, txtManualFolderSelection.Text.Count + 1)
            Dim movieName = direc.Remove(0, txtManualFolderSelection.Text.Count)
            movieName = movieName.Replace("\", "")
            Dim s As New KeyValuePair(Of String, String)(direc, movieName)
            mvAry.Add(s)
        Next
        lstMovies.DataSource = mvAry
        lstMovies.DisplayMember = "Value"
        lstMovies.SelectionMode = SelectionMode.One
    End Sub
    Private Sub populateMovieListBatch()
        lstMoviesBatch.SelectionMode = SelectionMode.None
        Dim directoryList As String() ' array for directories
        If chkUnprocessedOnly.Checked Then
            directoryList = hideProcessedFolders(IO.Directory.GetDirectories(txtBatchProcess.Text))
        Else
            directoryList = IO.Directory.GetDirectories(txtBatchProcess.Text)
        End If
        direcListBatch = directoryList
        Dim movieArray As New ArrayList
        Dim mvAry As New List(Of KeyValuePair(Of String, String))

        For Each direc In directoryList
            'Dim movieName = direc.Remove(0, txtBatchProcess.Text.Count + 1)
            Dim movieName = direc.Remove(0, txtBatchProcess.Text.Count)
            movieName = movieName.Replace("\", "")
            Dim s As New KeyValuePair(Of String, String)(direc, movieName)
            mvAry.Add(s)
        Next
        lstMoviesBatch.DataSource = mvAry
        lstMoviesBatch.DisplayMember = "Value"
        '  lstMovies.SelectionMode = SelectionMode.One
    End Sub

    Private Function hideProcessedFolders(ByVal direcList() As String) As String()
        Dim currentDirec As IO.Directory
        Dim sRetObj As New List(Of String)

        Try
            For Each direc In direcList
                Dim files = IO.Directory.GetFiles(direc)
                Dim bFound As Boolean = False
                For Each f In files
                    If f.Equals(direc & "\" & My.Settings.MovieSheetName) = True Then
                        bFound = True
                    End If
                Next
                If bFound = False Then
                    sRetObj.Add(direc)
                End If
            Next
            Return sRetObj.ToArray
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Function

    Private Sub lstMovies_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstMovies.SelectedIndexChanged
        Try
            clearMovieInfo()
            Dim s As KeyValuePair(Of String, String)
            s = lstMovies.SelectedItem
            'first check and show any existing moviesheet
            Dim direcInfo As New IO.DirectoryInfo(s.Key)
            Dim files = direcInfo.GetFiles(My.Settings.MovieSheetName)
            bmpVideoResolution = Nothing
            bmpAudioFormat = Nothing
            bmpAudioFormat2 = Nothing
            bmpFiletype = Nothing
            bmpFiletype2 = Nothing
            'If wd_tv.jpg already exists. 
            If files.Length <> 0 Then
                txtManualLog.Clear()
                'pnlMovieInfo.Visible = False
                'btnEditMovieInfo.Text = "EDIT"
                'pbExistingSheet.Size = New Size(960, 540)
                pbExistingSheet.Size = New Size(640, 360)
                Dim file = files.First
                loadedBitmap = Nothing
                loadedBitmap = New Bitmap(file.FullName)
                pnlCreateSheet.Visible = False
                btnRedo.Visible = True
                btnRedoWithTemplate.Visible = True
                btnGenerate.Visible = False
                pbExistingSheet.Image = loadedBitmap
                pbExistingSheet.Visible = True
                pbExistingSheet.BringToFront()
                pbExistingSheet.SizeMode = PictureBoxSizeMode.Zoom
                PictureBox1.Image = loadedBitmap
                'pnlApplyTemplate.Visible = True
                If IO.File.Exists(s.Key & "\Movie_Info.xml") = True Then
                    'btnEditMovieInfo.Visible = True
                    clearMovieInfo()
                    LoadXML(s.Key & "\Movie_Info.xml")
                    '               Else
                    '                    btnEditMovieInfo.Visible = False
                Else
                    'clearMovieInfo()
                End If
                Application.DoEvents()
                'File wd_tv.jpg doesn't exists
            Else
                'pnlApplyTemplate.Visible = False
                'clearMovieInfo()
                loadedBitmap = Nothing
                pbExistingSheet.Visible = False
                pnlCreateSheet.Visible = True
                btnRedo.Visible = False
                btnRedoWithTemplate.Visible = False
                btnGenerate.Visible = True
                '*********bit of house keeping**********
                bNotFoundOnIMDB = False
                bNotFoundOnMovieDB = False
                txtManualLog.Text = ""
                lstBackdrops.Items.Clear()
                lstPoster.Items.Clear()
                'lstPoster.DataSource = Nothing
                pbBackdropPreview.Image = Nothing
                pbPosterPreview.Image = Nothing
                aryBackdrops.Clear()
                aryPosters.Clear()
                'btnMoreFound.Visible = False
                Application.DoEvents()
                '**************************************
                Cursor.Current = Cursors.WaitCursor
                If My.Settings.PrimarySource = "MovieDB" Then
                    Dim movieID = SearchOnTMDb_manual(s.Value)
                    If movieID <> 0 Then
                        LogManual("Movie Found ID:" & movieID.ToString, 1)
                        populateBackdrops(movieID)
                        populatePosters()
                        getMovieInfo(SearchOnTMDb_manual(direcInfo.Name))
                        populateMovieInfo()
                        Application.DoEvents()
                    Else
                        LogManual("...Movie not found...", 1)
                    End If
                Else
                    'use IMDB as primary source
                    SearchOnIMDb(s.Value, 0)
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub
    Private Sub clearMovieInfo()
        txtTitle.Text = ""
        txtSummary.Text = ""
        txtRating.Text = ""
        txtRunTime.Text = ""
        txtActors.Text = ""
        txtGenres.Text = ""
        txtYear.Text = ""
        txtDirectors.Text = ""
        txtCertification.Text = ""
        txtOriginalTitle.Text = ""
        txtCountries.Text = ""
        txtStudios.Text = ""
        txtTagline.Text = ""
        My.Settings.DisplayAspectRatio = ""

        'lbWarning NOT DECLARED!!
        'lbWarning.Text = ""
    End Sub
    Private Sub populateMovieInfo()
        Try

            clearMovieInfo()
            LogManual("Retrieving Movie Information ... ", 0)
            Dim doc As New XDocument
            doc = currentDoc
            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c
            If q.Count = 0 Then
                logMultiThread("not found", 1)
            Else
                Dim firstOBJ = q.ElementAt(0)
                If CStr(firstOBJ).IndexOf("Nothing found") <> -1 Then
                    firstOBJ = Nothing
                End If

                If My.Settings.PrimarySource = "MovieDB" And bNotFoundOnMovieDB = False Then

                    txtTitle.Text = System.Web.HttpUtility.HtmlDecode(firstOBJ.Element("name").Value)

                    txtOriginalTitle.Text = (System.Web.HttpUtility.HtmlDecode(firstOBJ.Element("original_name").Value))

                    txtSummary.Text = firstOBJ.Element("overview").Value
                    txtRating.Text = firstOBJ.Element("rating").Value & "/10"
                    txtRunTime.Text = firstOBJ.Element("runtime").Value
                    txtYear.Text = Mid(firstOBJ.Element("released").Value, 1, 4)

                    txtTagline.Text = firstOBJ.Element("tagline").Value

                    'Genre
                    Dim q1 = From c1 In q.Elements("categories").Elements("category") _
                    Where c1.Attribute("type") = "genre" _
                    Select c1
                    For Each genre In q1
                        txtGenres.Text = txtGenres.Text & genre.Attribute("name").Value & ", "
                    Next
                    If txtGenres.Text.EndsWith(", ") Then
                        txtGenres.Text = txtGenres.Text.Remove(txtGenres.Text.Length - 2, 2)
                    End If

                    'Cast
                    q1 = From c1 In q.Elements("cast").Elements("person") _
                    Where c1.Attribute("job") = "Actor" _
                    Select c1
                    For Each actor In q1
                        txtActors.Text = txtActors.Text & System.Web.HttpUtility.HtmlDecode(actor.Attribute("name").Value) & ", "
                    Next
                    If txtActors.Text.EndsWith(", ") Then
                        txtActors.Text = txtActors.Text.Remove(txtActors.Text.Length - 2, 2)
                    End If

                    'Directors

                    q1 = From c1 In q.Elements("cast").Elements("person") _
                    Where c1.Attribute("job") = "Director" _
                    Select c1

                    For Each director In q1

                        txtDirectors.Text = txtDirectors.Text & director.Attribute("name").Value & ", "

                    Next

                    If txtDirectors.Text.EndsWith(", ") Then

                        txtDirectors.Text = txtDirectors.Text.Remove(txtDirectors.Text.Length - 2, 2)

                    End If

                    'Certification
                    txtCertification.Text = firstOBJ.Element("certification").Value

                    'Countries
                    Dim q2 = From c1 In q.Elements("countries").Elements("country")

                    For Each country In q2

                        txtCountries.Text = txtCountries.Text & country.Attribute("name").Value & ", "

                    Next

                    If txtCountries.Text.EndsWith(", ") Then

                        txtCountries.Text = txtCountries.Text.Remove(txtCountries.Text.Length - 2, 2)

                    End If

                    'Studios 
                    Dim q3 = From c1 In q.Elements("studios").Elements("studio")

                    For Each studio In q3

                        txtStudios.Text = txtStudios.Text & studio.Attribute("name").Value & ", "

                    Next

                    If txtStudios.Text.EndsWith(", ") Then

                        txtStudios.Text = txtStudios.Text.Remove(txtStudios.Text.Length - 2, 2)

                    End If

                Else
                    'use imdbInfo
                    If currentTitle.Title <> vbNullString Then
                        ' apostrophies come back wierd. this line boxes that off.
                        currentTitle.Title = currentTitle.Title.Replace("&#x27;", "'")
                        If currentTitle.Title.Contains("IMDb - ") Then
                            currentTitle.Title = currentTitle.Title.Replace("IMDb - ", "")
                        End If
                        txtTitle.Text = System.Web.HttpUtility.HtmlDecode(currentTitle.Title)

                    ElseIf firstOBJ IsNot Nothing Then
                        txtTitle.Text = System.Web.HttpUtility.HtmlDecode(firstOBJ.Element("name").Value)
                    End If

                    If firstOBJ IsNot Nothing Then
                        txtOriginalTitle.Text = System.Web.HttpUtility.HtmlDecode(firstOBJ.Element("original_name").Value)
                    End If

                    txtTagline.Text = firstOBJ.Element("tagline").Value

                    If currentTitle.Plot <> vbNullString Then
                        txtSummary.Text = currentTitle.Plot.Replace("|", "")
                        txtSummary.Text = System.Web.HttpUtility.HtmlDecode(txtSummary.Text)
                    ElseIf firstOBJ IsNot Nothing Then
                        txtSummary.Text = firstOBJ.Element("overview").Value
                    End If

                    If currentTitle.Rating <> vbNullString Then
                        txtRating.Text = currentTitle.Rating & "/10"
                    ElseIf firstOBJ IsNot Nothing Then
                        txtRating.Text = firstOBJ.Element("rating").Value & "/10"

                    End If

                    If currentTitle.Runtime <> vbNullString Then
                        txtRunTime.Text = currentTitle.Runtime
                    ElseIf firstOBJ IsNot Nothing Then
                        txtRunTime.Text = firstOBJ.Element("runtime").Value
                    End If

                    If currentTitle.Actors IsNot Nothing Then
                        For Each actor In currentTitle.Actors
                            txtActors.Text = System.Web.HttpUtility.HtmlDecode(txtActors.Text) & actor.Name & ", "
                        Next
                        If txtActors.Text.EndsWith(", ") Then
                            txtActors.Text = txtActors.Text.Remove(txtActors.Text.Length - 2, 2)
                        End If
                    Else
                        Dim q1 = From c1 In q.Elements("cast").Elements("person") _
                            Where c1.Attribute("job") = "Actor" _
                            Select c1
                        For Each actor In q1
                            txtActors.Text = txtActors.Text & System.Web.HttpUtility.HtmlDecode(actor.Attribute("name").Value) & ", "
                        Next

                        If txtActors.Text.EndsWith(", ") Then
                            txtActors.Text = txtActors.Text.Remove(txtActors.Text.Length - 2, 2)
                        End If
                    End If

                    If currentTitle.Genres IsNot Nothing Then

                        For Each genre In currentTitle.Genres
                            txtGenres.Text = txtGenres.Text & genre & ", "
                        Next
                    Else
                        Dim q1 = From c1 In q.Elements("categories").Elements("category") _
                    Where c1.Attribute("type") = "genre" _
                    Select c1
                        For Each genre In q1
                            txtGenres.Text = txtGenres.Text & genre.Attribute("name").Value & ", "
                        Next
                    End If
                    If txtGenres.Text.EndsWith(", ") Then
                        txtGenres.Text = txtGenres.Text.Remove(txtGenres.Text.Length - 2, 2)
                    End If

                    If currentTitle.Directors IsNot Nothing Then
                        For Each director In currentTitle.Directors
                            txtDirectors.Text = txtDirectors.Text & director.Name & ", "
                        Next
                    Else
                        Dim q1 = From c1 In q.Elements("cast").Elements("person") _
                            Where c1.Attribute("job") = "Director" _
                            Select c1
                        For Each director In q1
                            txtDirectors.Text = txtDirectors.Text & director.Attribute("name").Value & ", "
                        Next
                    End If

                    If txtDirectors.Text.EndsWith(", ") Then
                        txtDirectors.Text = txtDirectors.Text.Remove(txtDirectors.Text.Length - 2, 2)
                    End If

                    If currentTitle.Year <> vbNullString Then
                        txtYear.Text = currentTitle.Year
                    Else
                        txtYear.Text = Mid(firstOBJ.Element("released").Value, 1, 4)
                    End If

                    txtCertification.Text = firstOBJ.Element("certification").Value

                    Dim q2 = From c1 In q.Elements("countries").Elements("country")
                    For Each country In q2
                        txtCountries.Text = txtCountries.Text & country.Attribute("name").Value & ", "
                    Next
                    If txtCountries.Text.EndsWith(", ") Then
                        txtCountries.Text = txtCountries.Text.Remove(txtCountries.Text.Length - 2, 2)
                    End If

                    Dim q3 = From c1 In q.Elements("studios").Elements("studio")
                    For Each studio In q3
                        txtStudios.Text = txtStudios.Text & studio.Attribute("name").Value & ", "
                    Next

                    If txtStudios.Text.EndsWith(", ") Then
                        txtStudios.Text = txtStudios.Text.Remove(txtStudios.Text.Length - 2, 2)
                    End If


                    End If
                logMultiThread("done", 1)

                btnGo.Visible = True

            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
        End Try
    End Sub
    Private Sub populateBackdropsIMDB(ByVal imdbID As String)
        Dim httpReq As HttpWebRequest
        Dim httpResponse As HttpWebResponse
        Dim language As String
        language = getLanguageCode()

        Try
            logMultiThread("Downloading Backdrops ... ", 0)
            Cursor.Current = Cursors.WaitCursor
            httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBIMDBLookup, language, API_KEY, imdbID))
            httpResponse = httpReq.GetResponse
            Dim stream = httpResponse.GetResponseStream
            Dim doc As New XDocument
            Dim reader As New XmlTextReader(stream)
            doc = XDocument.Load(reader)
            currentDoc = doc

            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c

            If q.Count = 0 Then
                logMultiThread("No Backdrops available in IMDB.", 1)

            Else
                Dim firstOBJ = q.ElementAt(0)
                'getInfo from movieDB.org to include cast
                Dim iMovieDBId = firstOBJ.Element("id").Value
                httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBGetInfoUrl, language, API_KEY, iMovieDBId))
                'httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBGetInfoUrl, language, API_KEY, iMovieDBId))
                httpResponse = httpReq.GetResponse
                stream = httpResponse.GetResponseStream
                reader = New XmlTextReader(stream)
                doc = XDocument.Load(reader)
                currentDoc = doc

                Dim q1 = From c1 In q.Elements("images").Elements("image") _
                       Where c1.Attribute("type") = "backdrop" And c1.Attribute("size") = "original" _
                       Select c1

                If q1.Count = 0 Then
                    logMultiThread("No Backdrops Available for this Movie.", 1)
                    'load default backdrop
                    If My.Settings.DefaultBackdrop <> vbNullString Then
                        Dim bmp As New Bitmap(My.Settings.DefaultBackdrop)
                        Dim newBAckdrop = New KeyValuePair(Of Bitmap, String)(bmp, "SelectedBackdrop")
                        aryBackdrops.Add(newBAckdrop)
                        'lstBackdrops.DataSource = Nothing
                        'lstBackdrops.DataSource = aryBackdrops
                        'lstBackdrops.DisplayMember = "Value"
                        populateBackdropsList()
                    End If
                Else
                    aryBackdrops.Clear()
                    'Dim aryBAckdrops As New List(Of KeyValuePair(Of Bitmap, String))
                    Dim iCount As Integer = 0
                    ReDim resetEvents(q1.Count - 1)

                    For Each backdrop In q1
                        Dim params(1) As String
                        params(0) = backdrop.Attribute("url").Value
                        params(1) = iCount.ToString

                        ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf GetBackdrop), params)
                        resetEvents(iCount) = New ManualResetEvent(False)

                        iCount += 1
                    Next
                    WaitHandle.WaitAll(resetEvents)
                    populateBackdropsList()
                    'lstBackdrops.DataSource = Nothing
                    'lstBackdrops.DataSource = aryBackdrops
                    'lstBackdrops.DisplayMember = "Value"

                    logMultiThread(q1.Count.ToString & " found", 1)
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally

        End Try


    End Sub
    Private Sub populateBackdropsList()
        Try
            Dim Num_Image As Integer = 1
            lstBackdrops.Items.Clear()
            clearFanArt()
            For Each ary In aryBackdrops
                Dim lvi As New ListViewItem
                'lvi.Text = ary.Value
                lvi.Text = "Backdrop " & Num_Image
                Num_Image = Num_Image + 1
                Dim s As New KeyValuePair(Of Bitmap, String)(ary.Key, ary.Value)
                lvi.Tag = s
                lstBackdrops.Items.Add(lvi)
            Next

            lstBackdrops.Items(0).Selected = True
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally

        End Try
    End Sub

    Private Sub populatePostersList()
        Try
            Dim Num_Image As Integer = 1
            lstPoster.Items.Clear()
            clearFanArt()
            For Each ary In aryPosters
                Dim lvi As New ListViewItem
                'lvi.Text = ary.Value
                lvi.Text = "Poster " & Num_Image
                Num_Image = Num_Image + 1
                Dim s As New KeyValuePair(Of Bitmap, String)(ary.Key, ary.Value)
                lvi.Tag = s
                lstPoster.Items.Add(lvi)
            Next

            lstPoster.Items(0).Selected = True
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally

        End Try
    End Sub

    Private Sub clearFanArt()
        mnuFanArt1.Checked = False
        mnuFanArt2.Checked = False
        mnuFanArt3.Checked = False
        bmpFanArt1 = Nothing
        bmpFanArt2 = Nothing
        bmpFanArt3 = Nothing
    End Sub

    Private Sub populateBackdrops(ByVal movieID As Integer)
        Dim httpReq As HttpWebRequest
        Dim httpResponse As HttpWebResponse
        Dim language As String
        language = getLanguageCode()
        Try
            'logMultiThread("Downloading Backdrops ... ", 0)
            Cursor.Current = Cursors.WaitCursor
            httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBGetInfoUrl, language, API_KEY, movieID.ToString))
            'httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBGetInfoUrl, API_KEY, movieID.ToString))
            'logMultiThread("Getting Movie Info", 1)
            httpResponse = httpReq.GetResponse
            Dim stream = httpResponse.GetResponseStream
            'logMultiThread("Movie Info Received", 1)
            Dim doc As New XDocument
            Dim reader As New XmlTextReader(stream)
            doc = XDocument.Load(reader)
            currentDoc = doc
            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c
            Dim firstOBJ = q.ElementAt(0)

            Dim q1 = From c1 In q.Elements("images").Elements("image") _
                   Where c1.Attribute("type") = "backdrop" And c1.Attribute("size") = "poster" _
                   Select c1
            aryBackdrops.Clear()
            'Dim aryBAckdrops As New List(Of KeyValuePair(Of Bitmap, String))
            Dim iCount As Integer = 0
            ReDim resetEvents(q1.Count - 1)

            logMultiThread("Downloading Backdrops ... ", 0)


            For Each backdrop In q1
                Dim params(1) As String
                params(0) = backdrop.Attribute("url").Value
                params(1) = iCount.ToString

                ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf GetBackdrop), params)
                resetEvents(iCount) = New ManualResetEvent(False)

                iCount += 1
            Next

            If q1.Count > 0 Then

                WaitHandle.WaitAll(resetEvents)

                populateBackdropsList()

            Else

                If My.Settings.DefaultBackdrop <> vbNullString Then

                    Dim bmp As New Bitmap(My.Settings.DefaultBackdrop)
                    Dim newBAckdrop = New KeyValuePair(Of Bitmap, String)(bmp, "SelectedBackdrop")
                    aryBackdrops.Add(newBAckdrop)

                    populateBackdropsList()

                End If


            End If

            'lstBackdrops.DataSource = Nothing
            'lstBackdrops.DataSource = aryBackdrops
            'lstBackdrops.DisplayMember = "Value"
            'populateBackdropsList()
            logMultiThread(q1.Count.ToString & " found", 1)
            'logMultiThread("There are " & q1.Count.ToString & " backdrops available for this movie", 1)

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            Cursor.Current = Cursors.Default
        End Try

    End Sub
    Private Sub populateBAckdropPreview(ByVal bmpbackdrop As Bitmap)

        pbBackdropPreview.Image = bmpbackdrop
        pbBackdropPreview.SizeMode = PictureBoxSizeMode.StretchImage
    End Sub
    Private Sub getIMDBPoster(ByVal sUrl As String)
        Try
            If sUrl <> vbNullString Then
                LogManual("Downloading IMDB Poster ... ", 0)
                aryPosters.Clear()
                Dim httpReq1 As HttpWebRequest
                Dim httpResponse1 As HttpWebResponse
                httpReq1 = WebRequest.Create(sUrl)
                httpResponse1 = httpReq1.GetResponse
                Dim bmpPoster As New Bitmap(httpResponse1.GetResponseStream)

                Dim newPoster = New KeyValuePair(Of Bitmap, String)(bmpPoster, "IMDBPoster")
                aryPosters.Add(newPoster)
                Application.DoEvents()
                'lstPoster.DataSource = Nothing
                'lstPoster.DataSource = aryPosters
                'lstPoster.DisplayMember = "Value"
                LogManual("Done", 1)
            Else
                LogManual("No IMDB Poster Available.", 1)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub populatePosters()
        Try
            Dim doc As New XDocument
            doc = currentDoc
            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c

            Dim q1 = From c1 In q.Elements("images").Elements("image") _
                   Where c1.Attribute("type") = "poster" And c1.Attribute("size") = "original" _
                                Select c1

            If q1.Count = 0 Then
                logMultiThread("There are no poster available on TheMoviedb.org for this movie.", 1)
                logMultiThread("Attempting on IMDB", 1)
                getIMDBPoster(currentTitle.CoverURL)
            Else
                LogManual("Downloading Posters ... ", 0)
                aryPosters.Clear()
                Dim iCount As Integer = 0
                ReDim resetEventsPoster(q1.Count - 1)
                For Each poster In q1

                    Dim params(1) As String
                    params(0) = poster.Attribute("url").Value
                    params(1) = iCount.ToString

                    ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf GetPoster), params)
                    resetEventsPoster(iCount) = New ManualResetEvent(False)

                    iCount += 1
                Next
                WaitHandle.WaitAll(resetEventsPoster)
                populatePostersList()
                'lstPoster.DataSource = Nothing
                'lstPoster.DataSource = aryPosters
                'lstPoster.DisplayMember = "Value"
                LogManual(q1.Count.ToString & " found", 1)
                'LogManual("There are " & q1.Count.ToString & " posters available for this movie", 1)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub GetBackdrop(ByVal objIN As Object)
        Dim iCount = CInt(objIN(1))
        Try

            Dim url = CStr(objIN(0))

            ' logMultiThread("Getting backdrop " & url)
            Dim httpReq1 As HttpWebRequest
            Dim httpResponse1 As HttpWebResponse
            httpReq1 = WebRequest.Create(url)
            httpResponse1 = httpReq1.GetResponse
            Dim bmpBackdrop As New Bitmap(httpResponse1.GetResponseStream)
            ' Dim sImgID = backdrop.Attribute("id").Value
            ' Dim sUrlToRemove = String.Format(sImgUrl, sImgID)
            Dim sImgName = url.Replace(sImgUrl, "")
            sImgName = sImgName.Replace("_poster", "")
            Dim newBAckdrop = New KeyValuePair(Of Bitmap, String)(bmpBackdrop, sImgName)
            aryBackdrops.Add(newBAckdrop)
        Catch ex As Exception
        Finally
            resetEvents(iCount).Set()
        End Try
    End Sub
    Private Sub GetPoster(ByVal objIN As Object)
        Dim url = objIN(0)
        Dim iCount = objIN(1)
        Try
            Dim httpReq1 As HttpWebRequest
            Dim httpResponse1 As HttpWebResponse
            httpReq1 = WebRequest.Create(url)
            httpResponse1 = httpReq1.GetResponse
            Dim bmpPoster As New Bitmap(httpResponse1.GetResponseStream)
            Dim sImgName = url.Replace(sImgUrlPoster, "")
            sImgName = sImgName.Replace("_thumb", "")
            Dim newPoster = New KeyValuePair(Of Bitmap, String)(bmpPoster, sImgName)
            aryPosters.Add(newPoster)
        Catch ex As Exception
        Finally
            resetEventsPoster(iCount).Set()
        End Try
    End Sub
    Private Sub lstBackdrops_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstBackdrops.SelectedIndexChanged
        If lstBackdrops.SelectedItems.Count > 0 Then
            Dim s As New KeyValuePair(Of Bitmap, String)
            s = lstBackdrops.SelectedItems(0).Tag
            populateBAckdropPreview(s.Key)
        End If

    End Sub

    Private Sub lstPoster_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstPoster.SelectedIndexChanged
        If lstPoster.SelectedItems.Count > 0 Then
            Dim s As New KeyValuePair(Of Bitmap, String)
            s = lstPoster.SelectedItems(0).Tag
            pbPosterPreview.Image = s.Key
            pbPosterPreview.SizeMode = PictureBoxSizeMode.StretchImage
        End If

    End Sub

    Private Sub btnBackdropPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBackdropPreview.Click
        If pbBackdropPreview.Image Is Nothing Then
            MsgBox("Nothing to preview as no backdrop selected")
        Else
            Dim s As New KeyValuePair(Of Bitmap, String)

            s = lstBackdrops.SelectedItems(0).Tag

            PictureBox2.Image = getHDImage(s.Value, True)
            TabControl1.SelectedTab = TabPage4
        End If
    End Sub
    Private Function getHDImage(ByVal sValue As String, ByVal bIsBackdrop As Boolean) As Bitmap
        Try


            If sValue = "IMDBPoster" Or sValue = "SelectedBackdrop" Or sValue = "SelectedPoster" Then
                If bIsBackdrop Then
                    Dim s As New KeyValuePair(Of Bitmap, String)
                    s = lstBackdrops.SelectedItems(0).Tag
                    Return s.Key
                Else
                    Dim s As New KeyValuePair(Of Bitmap, String)
                    's = lstPoster.SelectedItems(0).Tag
                    s = lstPoster.SelectedItems(0).tag
                    Return s.Key
                End If
            Else
                Dim httpReq1 As HttpWebRequest
                Dim httpResponse1 As HttpWebResponse
                Dim sFileName = sValue
                If sFileName.IndexOf(".jpg") = -1 Then
                    sFileName = sFileName & ".jpg"
                End If
                If bIsBackdrop Then
                    'THIS STOP WORK WE DON'T KNOW WHY.
                    'httpReq1 = WebRequest.Create(sImgUrl & sFileName)

                    'FIX TO WORK AGAIN
                    httpReq1 = WebRequest.Create(sFileName)
                Else
                    'THIS STOP WORK WE DON'T KNOW WHY.
                    'httpReq1 = WebRequest.Create(sImgUrlPoster & sFileName)

                    'FIX TO WORK AGAIN
                    httpReq1 = WebRequest.Create(sFileName)
                End If

                httpResponse1 = httpReq1.GetResponse
                Dim bmpHDImage As New Bitmap(httpResponse1.GetResponseStream)
                Return bmpHDImage


            End If
        Catch ex As Exception
            MessageBox.Show("For some reason the selected " & IIf(bIsBackdrop, "Backdrop", "Poster") & " could not be found. Please select a different one and try again")
        End Try
    End Function

    Private Sub btnGenerate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerate.Click
        Try
            'If sDefaultTemplatePath <> vbNullString And My.Settings.UseOriginal = False Then
            If sDefaultTemplatePath <> vbNullString Or My.Settings.UseOriginal = True Then

                'LogManual("Generating New Image. Please wait...", 1)
                Cursor.Current = Cursors.WaitCursor
                Dim s As New KeyValuePair(Of String, String)
                Dim selectedBackdrop As New KeyValuePair(Of Bitmap, String)
                Dim selectedPoster As New KeyValuePair(Of Bitmap, String)
                selectedBackdrop = lstBackdrops.SelectedItems(0).Tag
                selectedPoster = lstPoster.SelectedItems(0).Tag
                s = lstMovies.SelectedItem

                'If My.Settings.AnalyseMKVs Then
                '    LogManual("AnalyseMKV True", 1)
                'Else
                '    LogManual("AnalyseMKV False", 1)
                'End If

                'If cbManuallyInput.Checked Then
                '    LogManual("Manual Stream Input True", 1)
                'Else
                '    LogManual("Manual Stream Input False", 1)
                'End If

                'If bNotFoundOnMovieDB = False Then
                '    Dim doc As New XDocument
                '    doc = currentDoc

                '    Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                '            Select c
                '    Dim firstOBJ = q.ElementAt(0)
                'End If

                If My.Settings.AnalyseMKVs And cbManuallyInput.Checked = False Then
                    AnalyseMovie(s)
                    'User wants to manually input
                Else
                    ManuallyCreateVideoAudioFormat()
                End If

                Dim sTitle As String = txtTitle.Text
                Dim sSummary As String = txtSummary.Text
                Dim sRating As String = txtRating.Text.ToString
                Dim sRunTime As String = txtRunTime.Text.ToString
                LogManual("Downloading Selected Backdrop ... ", 0)
                Dim hdBackdrop = getHDImage(selectedBackdrop.Value, True)
                LogManual("Done", 1)
                Dim hdposter As Bitmap
                Dim bmpFolderImage As New Bitmap(My.Settings.CoverWidth, My.Settings.CoverHeight)

                Dim newsheet As New Bitmap(1280, 720, Imaging.PixelFormat.Format32bppArgb)
                Dim b = Graphics.FromImage(newsheet)

                LogManual("Downloading Selected Poster ... ", 0)
                'hdposter = getHDImage(selectedPoster.Value, False)
                hdposter = selectedPoster.Key
                LogManual("Done", 1)
                Dim g = Graphics.FromImage(bmpFolderImage)
                Dim coverRect As New Rectangle(0, 0, My.Settings.CoverWidth, My.Settings.CoverHeight)

                g.DrawImage(hdposter, coverRect)
                If chkUseOriginal.Checked = False Then
                    createdImage = ApplyTemplate(sDefaultTemplatePath, hdBackdrop, hdposter)
                Else
                    createdImage = generateImage(hdposter, hdBackdrop, sTitle, sSummary, sRunTime, sRating)
                End If

                If My.Settings.ExportCover Then
                    bmpFolderImage.Save(s.Key & "\" & My.Settings.CoverName, Imaging.ImageFormat.Jpeg)
                End If


                PictureBox1.Image = createdImage
                createdImage.Save(s.Key & "\" & My.Settings.MovieSheetName, Imaging.ImageFormat.Jpeg)


                If My.Settings.UseCache Then
                    GenerateXML(s.Key)
                    'MUDAR AQUI O BACKDROP.   e:\filme\
                    Dim Dir As String
                    hdBackdrop.Save(s.Key & "\backdrop.jpg", Imaging.ImageFormat.Jpeg)
                    hdposter.Save(s.Key & "\cover.jpg", Imaging.ImageFormat.Jpeg)
                    If bmpFanArt1 IsNot Nothing Then
                        bmpFanArt1.Save(s.Key & "\fanart1.jpg")
                    End If
                    If bmpFanArt2 IsNot Nothing Then
                        bmpFanArt2.Save(s.Key & "\fanart2.jpg")
                    End If
                    If bmpFanArt3 IsNot Nothing Then
                        bmpFanArt3.Save(s.Key & "\fanart3.jpg")
                    End If
                End If

                If chkShowcase.Checked Then
                    '**** backdrop resizing, cropping & renaming start ****
                    b.InterpolationMode = InterpolationMode.High
                    b.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
                    b.DrawImage(hdBackdrop, 0, 0, 1280, 720)
                    newsheet.SetResolution(1280, 720)

                    '**** cropping starts here
                    Dim CroppedImage As New Bitmap(1280, 459)
                    Dim h = Graphics.FromImage(CroppedImage)
                    h.DrawImage(newsheet, New Rectangle(0, 0, CroppedImage.Width, CroppedImage.Height), 0, 0, CroppedImage.Width, CroppedImage.Height, GraphicsUnit.Pixel)
                    h.DrawImage(My.Resources.Images.diffuse, New Rectangle(0, CroppedImage.Height - My.Resources.Images.diffuse.Height, 1280, 459), 0, 0, 1280, 459, GraphicsUnit.Pixel)
                    h.Dispose()
                    CroppedImage.Save(s.Key & "_sheet.jpg", Imaging.ImageFormat.Jpeg)
                    '**** backdrop resizing, cropping & renaming end ****
                    LogManual("Showcase backdrop generated successfully...", 1)

                End If

                If Msheet_T_b_s.Checked Then
                    b.InterpolationMode = InterpolationMode.High
                    b.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
                    b.DrawImage(hdBackdrop, 0, 0, 1280, 720)
                    newsheet.SetResolution(1280, 720)
                    Dim h = Graphics.FromImage(hdBackdrop)
                    h.DrawImage(hdBackdrop, New Rectangle(0, 0, newsheet.Width, newsheet.Height), 0, 0, newsheet.Width, newsheet.Height, GraphicsUnit.Pixel)
                    newsheet.Save(s.Key & "_sheet.jpg", Imaging.ImageFormat.Jpeg)
                End If

                LogManual("Moviesheet generated successfully", 1)

                txtOverride.Text = ""

            Else
                MessageBox.Show("There is no default template selected. Please select a default template from the settings tab.", "Hold on a sec...", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
            End If
            'lstMovies_SelectedIndexChanged(sender, e)
            TabControl1.SelectTab(2)
        Catch ex As Exception
            MessageBox.Show(ex.Message)

        Finally
            Cursor.Current = Cursors.Default
        End Try

    End Sub

    Private Sub GenerateXML(ByVal path As String)
        Try
            Dim myXmlSettings As New XmlWriterSettings
            myXmlSettings.Indent = True
            myXmlSettings.NewLineOnAttributes = True

            Using ProductWriter As XmlWriter = XmlWriter.Create(path & "\Movie_Info.xml", myXmlSettings)

                ProductWriter.WriteComment("**bean_ian**WDTV Movie Generator**")
                ProductWriter.WriteStartElement("Movie")
                ProductWriter.WriteAttributeString("Title", txtTitle.Text)
                ProductWriter.WriteAttributeString("OriginalTitle", txtOriginalTitle.Text)
                ProductWriter.WriteAttributeString("Tagline", txtTagline.Text)
                ProductWriter.WriteAttributeString("Year", txtYear.Text)
                ProductWriter.WriteAttributeString("Runtime", txtRunTime.Text)
                ProductWriter.WriteAttributeString("Rating", txtRating.Text)
                ProductWriter.WriteAttributeString("Genres", txtGenres.Text)
                ProductWriter.WriteAttributeString("Plot", txtSummary.Text)
                ProductWriter.WriteAttributeString("Actors", txtActors.Text)
                ProductWriter.WriteAttributeString("Directors", txtDirectors.Text)
                ProductWriter.WriteAttributeString("Certification", txtCertification.Text)
                ProductWriter.WriteAttributeString("Countries", txtCountries.Text)
                ProductWriter.WriteAttributeString("Studios", txtStudios.Text)
                ProductWriter.WriteEndElement()

            End Using
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally

        End Try
    End Sub
    Private Sub generateSilent(ByVal sDirectory As String, ByVal sMovieName As String)
        Try

            getMovieInfo(SearchOnTMDb_manual(sMovieName))
            'save output files
            createdCover.Save(sDirectory & "\" & My.Settings.CoverName, Imaging.ImageFormat.Jpeg)
            createdImage.Save(sDirectory & "\" & My.Settings.MovieSheetName, Imaging.ImageFormat.Jpeg)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub
    Private Sub LogManual(ByVal sMsg As String, ByVal nPar As Integer)
        If nPar = 1 Then
            txtManualLog.AppendText(sMsg & vbCrLf)
            Application.DoEvents()
        Else
            txtManualLog.AppendText(sMsg)
            Application.DoEvents()
        End If
    End Sub
    Private Sub logMultiThread(ByVal sMsg As String, ByVal nPar As Integer)
        Me.Invoke(New UpdateTextHandler(AddressOf LogManual), sMsg, nPar)

    End Sub

    Private Sub btnGenerateNoText_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try

            Cursor.Current = Cursors.WaitCursor
            Dim s As New KeyValuePair(Of String, String)
            Dim selectedBackdrop As New KeyValuePair(Of Bitmap, String)
            Dim selectedPoster As New KeyValuePair(Of Bitmap, String)
            selectedBackdrop = lstBackdrops.SelectedItems(0).Tag
            selectedPoster = lstPoster.SelectedItems(0).Tag
            s = lstMovies.SelectedItem
            Dim doc As New XDocument
            doc = currentDoc

            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c
            Dim firstOBJ = q.ElementAt(0)
            Dim sTitle As String = firstOBJ.Element("name").Value
            Dim sSummary As String = firstOBJ.Element("overview").Value
            Dim sRating As String = Math.Round(CDbl(firstOBJ.Element("rating").Value), 2).ToString
            Dim sRunTime As String = firstOBJ.Element("runtime").Value
            createdImage = generateImage(getHDImage(selectedPoster.Value, False), getHDImage(selectedBackdrop.Value, True), "", "", sRunTime, sRating)
            createdImage.Save(s.Key & "\wd_tv.jpg", Imaging.ImageFormat.Jpeg)
            createdCover = selectedPoster.Key
            createdCover.Save(s.Key & "\folder.jpg", Imaging.ImageFormat.Jpeg)
            PictureBox1.Image = createdImage
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub btnSaveSetting_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveSetting.Click
        Try
            My.Settings.IncludeCover = chkIncludeCover.Checked
            My.Settings.IncludeRating = chkIncludeRating.Checked
            My.Settings.IncludeRuntime = chkIncludeRuntime.Checked
            My.Settings.IncludeSummary = chkIncludeSummary.Checked
            My.Settings.IncludeTitle = chkIncludeTitle.Checked
            My.Settings.DefaultBackdrop = txtDefaultBackdrop.Text
            My.Settings.CoverName = txtCoverName.Text
            My.Settings.MovieSheetName = txtMovieSheetName.Text
            My.Settings.CoverHeight = CInt(txtCoverHeight.Text)
            My.Settings.CoverWidth = CInt(txtCoverWidth.Text)
            My.Settings.UseCache = chkUseCache.Checked
            My.Settings.ExportCover = chkExportCoverImage.Checked
            If optIMDB.Checked Then
                My.Settings.PrimarySource = "IMDB"
            Else
                My.Settings.PrimarySource = "MovieDB"
            End If
            If optEnabled.Checked Then
                My.Settings.AnalyseMKVs = True
            Else
                My.Settings.AnalyseMKVs = False
            End If
            My.Settings.DolbyPath = txtDolbyDigital.Text
            My.Settings.DolbyStereoPath = TxtDolbyStereo.Text
            My.Settings.MPEGAudioPath = txtMPEGaudio.Text
            My.Settings.MPEGvideoPath = txtMPEGvideo.Text
            My.Settings.DTSPath = txtDTS.Text
            My.Settings.p1080 = txt1080.Text
            My.Settings.p720 = txt720.Text
            My.Settings.DvixPath = txtDivxIcon.Text
            My.Settings.H264Path = txtH264Icon.Text
            My.Settings.ISOPath = txtISOIcon.Text
            My.Settings.MKVPath = txtMKVIcon.Text
            My.Settings.AACPath = txtAACIcon.Text
            My.Settings.DVDPath = txtDVDIcon.Text
            My.Settings.XvidPath = txtXvidIcon.Text
            My.Settings.ISOPath = txtISOIcon.Text
            My.Settings.BluRayPath = txtBlueRayIcon.Text
            My.Settings.AAC51Path = TxtAAC51icon.Text
            My.Settings.FLACPath = TxtFLACicon.Text
            My.Settings.VorbisPath = txtVorbisIcon.Text
            My.Settings.Language = comboLanguage.SelectedIndex
            My.Settings.Showcase = chkShowcase.Checked
            My.Settings.Save()
            MsgBox("Settings Successfully Saved", vbOKOnly, "Save Settings")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub TabPage3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabPage3.Click

    End Sub

    Private Sub txtBatchProcess_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtBatchProcess.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf FolderBrowserDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()
        txtBatchProcess.Text = FolderBrowserDialog1.SelectedPath
    End Sub

    Private Sub chkUnprocessedOnly_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkUnprocessedOnly.CheckedChanged
        populateMovieListBatch()
    End Sub

    Private Sub chkUnprocessedOnlyManual_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkUnprocessedOnlyManual.CheckedChanged
        populateMovieList()
    End Sub

    Private Sub FileSystemWatcher1_Changed(ByVal sender As System.Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Created, FileSystemWatcher1.Changed, FileSystemWatcher1.Renamed, FileSystemWatcher1.Deleted
        populateMovieList()
        populateMovieListBatch()
    End Sub

    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Application.Exit()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Application.Exit()
    End Sub
    Delegate Sub UpdateTextHandler(ByVal strMessage As String, ByVal nPar As Integer)

    'Private Sub btnEditInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEditInfo.Click
    '
    '    If btnEditInfo.Text = "Hide Movie Info" Then
    '        pnlMovieInfo.Visible = False
    '        btnEditInfo.Text = "Edit Movie Info"
    '    Else
    '        pnlMovieInfo.Visible = True
    '        pnlMovieInfo.BringToFront()
    '        btnEditInfo.Text = "Hide Movie Info"
    '    End If
    'End Sub

    Private Sub SearchOnIMDb(ByVal sMovieName As String, ByVal iUseIMDBId As Integer)
        Try
            LogManual("Searching IMDB for " + sMovieName, 1)
            [error] = False
            imdbMgr = New IMDbManager
            Dim fields() As Boolean = {True, True, True, True, True, True, True, True, True, True, True}

            imdbMgr.parentErrorCaller = formErrorCaller
            imdbMgr.parentFunctionCaller = formFunctionCaller
            imdbMgr.parentProgressUpdaterCaller = formProgressCaller
            imdbMgr.IMDbSearch(iUseIMDBId, sMovieName, 0, -1, 0, 0, fields)
            'imdbMgr.IMDbSearch(1, "tt0458352", 0, -1, 0, 0, fields)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
        End Try
    End Sub
    Private Sub searchIMDBBatch(ByVal sMovieName As String, ByVal iUseIMDBId As Integer)
        Try
            Log("Searching IMDB for " + sMovieName)
            [error] = False
            imdbBatchMgr = New IMDbManager
            Dim fields() As Boolean = {True, True, True, True, True, True, True, True, True, True, True}

            imdbBatchMgr.parentErrorCaller = formBatchErrorCaller
            imdbBatchMgr.parentFunctionCaller = formBatchFunctionCaller
            imdbBatchMgr.parentProgressUpdaterCaller = formBatchProgressCaller
            imdbBatchMgr.IMDbSearch(iUseIMDBId, sMovieName, 0, -1, 0, 0, fields)

            'imdbMgr.IMDbSearch(1, "tt0458352", 0, -1, 0, 0, fields)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub txtDefaultBackdrop_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDefaultBackdrop.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()
        'thFolderSelection.
        ' If FolderBrowserDialog1.ShowDialog(Me) = 1 Then
        If OpenFileDialog1.FileName <> vbNullString Then
            txtDefaultBackdrop.Text = OpenFileDialog1.FileName
            My.Settings.DefaultBackdrop = txtDefaultBackdrop.Text
            My.Settings.Save()
        End If
    End Sub

    Private Sub btnSpecifyBackdrop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSpecifyBackdrop.Click
        OpenFileDialog1.FileName = vbNullString 'RG : shows emty filedialogbox
        OpenFileDialog1.Filter = "images (*.jpg) |*.jpg;"
        OpenFileDialog1.Title = "Select backdrop"

        Try
            Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
            thFolderSelection.SetApartmentState(ApartmentState.STA)
            thFolderSelection.IsBackground = True
            thFolderSelection.Start()
            thFolderSelection.Join()


            If OpenFileDialog1.FileName <> vbNullString Then
                'load selected backdrop into aryBackdrops
                Dim bmp As New Bitmap(OpenFileDialog1.FileName)
                Dim newBAckdrop = New KeyValuePair(Of Bitmap, String)(bmp, "SelectedBackdrop")
                aryBackdrops.Add(newBAckdrop)
                'lstBackdrops.DataSource=aryBackdrops
            Else : MessageBox.Show("No backdrop added/selected")

            End If

            populateBackdropsList()
            'lstBackdrops.DataSource = Nothing
            'lstBackdrops.DataSource = aryBackdrops
            'lstBackdrops.DisplayMember = "Value"
        Catch ex As Exception
            MessageBox.Show("No Backdrop selected")

        End Try

    End Sub

    Private Sub btnSpecifyPoster_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSpecifyPoster.Click
        OpenFileDialog1.FileName = vbNullString 'RG : shows emty filedialogbox
        OpenFileDialog1.Title = "Select poster"
        OpenFileDialog1.Filter = "images (*.jpg) |*.jpg;"

        If lstMovies.SelectedItem Is Nothing Then
            Try
                MessageBox.Show("No movie selected !")
            Catch ex As Exception

            End Try
        Else

            Try
                Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
                thFolderSelection.SetApartmentState(ApartmentState.STA)
                thFolderSelection.IsBackground = True
                thFolderSelection.Start()
                thFolderSelection.Join()

                If OpenFileDialog1.FileName <> vbNullString Then
                    'load selected backdrop into aryBackdrops
                    Dim bmp As New Bitmap(OpenFileDialog1.FileName)
                    Dim newPoster = New KeyValuePair(Of Bitmap, String)(bmp, "SelectedPoster")
                    aryPosters.Add(newPoster)
                    'lstBackdrops.DataSource = aryBackdrops
                End If
                'lstPoster.DataSource = Nothing
                'lstPoster.DataSource = aryPosters
                'lstPoster.DisplayMember = "Value"

                populatePostersList()

            Catch ex As Exception
                MessageBox.Show("No Poster selected")
            End Try
        End If

    End Sub

    'Private Sub btnMoreFound_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMoreFound.Click
    '    If Results.getInstance.ShowDialog = Windows.Forms.DialogResult.OK Then
    '        '*********bit of house keeping**********
    '        bNotFoundOnIMDB = False
    '        bNotFoundOnMovieDB = False
    '        btnGenerate.Visible = True
    '        btnRedoWithTemplate.Visible = False
    '        txtManualLog.Text = ""
    '        lstBackdrops.Items.Clear()
    '        lstPoster.Items.Clear()
    '        'lstPoster.DataSource = Nothing
    '        pbBackdropPreview.Image = Nothing
    '        pbPosterPreview.Image = Nothing
    '        aryBackdrops.Clear()
    '        aryPosters.Clear()
    '        Application.DoEvents()
    '        '**************************************
    '        imdbMgr.IMDbParse(Results.getInstance.Selected)
    '    End If
    'End Sub

    Private Sub getVideoInfo(ByVal fileName As String)
        bmpFiletype = Nothing
        bmpFiletype2 = Nothing
        bmpVideoResolution = Nothing
        bmpAudioFormat = Nothing
        bmpAudioFormat2 = Nothing

        My.Settings.Framerate = Nothing
        My.Settings.Filesize = Nothing
        My.Settings.DisplayAspectRatio = Nothing
        My.Settings.VideoWidth = Nothing
        My.Settings.VideoHeight = Nothing
        My.Settings.ResolutionName = Nothing
        My.Settings.SoundFormatName = Nothing
        My.Settings.SoundFormat2Name = Nothing
        My.Settings.VideoFormatName = Nothing
        My.Settings.MediaFormatName = Nothing


        LogManual("Getting Video & Audio Information", 1)
        Dim s As New Process
        Dim sinf As New ProcessStartInfo
        sinf.FileName = "MediaInfo.exe"
        sinf.Arguments = """" + fileName + """"
        sinf.RedirectStandardOutput = True
        sinf.CreateNoWindow = True
        sinf.UseShellExecute = False
        s = Process.Start(sinf)
        Dim readStream = s.StandardOutput
        Dim sResult = readStream.ReadToEnd
        '###################################
        '# Bitspyer
        '# Preparing Code for XML Parsing
        '###################################
        sinf.Arguments = "--Output=XML """"" + fileName + """"
        s = Process.Start(sinf)
        Dim XDoc As New XmlDocument()

        Try
            XDoc.Load(s.StandardOutput)
        Catch ex As Exception

        End Try

        Dim AllTrack As XmlNodeList = XDoc.SelectNodes("//track")

        'detect video
        Dim file = fileName.ToLower()
        'If LCase(sResult.IndexOf("Frame rate")) <> -1 Then
        Dim test As String()
        'test = sResult.Split(New [Char]() {"U+000A"})
        test = sResult.Split(New [Char]() {vbCrLf})
        Dim lenght = test.Length
        Dim i As Integer

        For i = 0 To lenght
            If lenght > i Then
                If test(i).Contains("File size") Then
                    Dim Filesize As String
                    Dim rg1 As String
                    rg1 = test(i).IndexOf(":")
                    test(i) = test(i).Substring(rg1 + 1)
                    Filesize = (test(i))
                    If Filesize.Contains("GiB") Then
                        Filesize = Filesize.Replace("GiB", "GB")
                    ElseIf Filesize.Contains("KiB") Then
                        Filesize = Filesize.Replace("KiB", "KB")
                    ElseIf Filesize.Contains("MiB") Then
                        Filesize = Filesize.Replace("MiB", "MB")
                    Else
                        'don't change format
                    End If
                    LogManual("Moviefile size is" & Filesize, 1)
                    My.Settings.Filesize = Filesize

                ElseIf test(i).Contains("Display aspect ratio") Then
                    Dim DAR As String
                    Dim rg2 As String
                    rg2 = test(i).IndexOf(":")
                    test(i) = test(i).Substring(rg2 + 1)
                    DAR = test(i)
                    LogManual("Display Aspect Ratio" & DAR, 1)
                    My.Settings.DisplayAspectRatio = DAR

                ElseIf test(i).Contains("Frame rate") And test(i).IndexOf("fps") <> -1 Then
                    Dim FR As String
                    Dim rg3 As String
                    rg3 = test(i).IndexOf(":")
                    test(i) = test(i).Substring(rg3 + 1)
                    FR = test(i)
                    FR = FR.Replace("fps", "")
                    FR = FR.Replace(" ", "")
                    LogManual("Frame rate is " & FR, 1)
                    My.Settings.Framerate = FR

                ElseIf test(i).Contains("Width") Then
                    Dim ResWidth As String
                    Dim rg4 As String
                    rg4 = test(i).IndexOf(":")
                    test(i) = test(i).Substring(rg4 + 1)
                    ResWidth = test(i)
                    ResWidth = ResWidth.Replace("pixels", "")
                    ResWidth = ResWidth.Replace(" ", "")
                    My.Settings.VideoWidth = ResWidth

                ElseIf test(i).Contains("Height") Then
                    Dim ResHeight As String
                    Dim rg5 As String
                    rg5 = test(i).IndexOf(":")
                    test(i) = test(i).Substring(rg5 + 1)
                    ResHeight = test(i)
                    ResHeight = ResHeight.Replace("pixels", "")
                    ResHeight = ResHeight.Replace(" ", "")
                    My.Settings.VideoHeight = ResHeight

                ElseIf test(i).Contains("Video") And test(i).IndexOf(":") = -1 Then
                    Dim Videostart As String
                    Videostart = i

                End If

            End If
        Next

        'End If

        If file.IndexOf("iso") <> -1 Then
            LogManual("ISO file found", 1)

            If My.Settings.ISOPath <> vbNullString Then
                bmpFiletype = New Bitmap(My.Settings.ISOPath)
            Else
                'LogManual("No ISO icon selected", 1)
            End If
        End If


        '******* MEDIAFORMAT DETECTION (START) ********

        If sResult.IndexOf("V_MPEG2") <> -1 Or sResult.IndexOf("MPEG Video") <> -1 Or sResult.IndexOf("MPEG-4") <> -1 Then
            LogManual("MPEG video detected.", 1)
            My.Settings.MediaFormatName = "MPEG"

            If My.Settings.MPEGvideoPath <> vbNullString Then
                bmpFiletype = New Bitmap(My.Settings.MPEGvideoPath)
            Else
                'LogManual("No MPEG video icon selected", 1)
            End If
        End If


        'If sResult.IndexOf("MPEG Video") <> -1 Then
        '    LogManual("MPEG video detected.", 1)
        '    My.Settings.MediaFormatName = "MPEG"

        '    If My.Settings.MPEGvideoPath <> vbNullString Then
        '        bmpFiletype = New Bitmap(My.Settings.MPEGvideoPath)
        '    Else
        '        'LogManual("No MPEG video icon selected", 1)
        '    End If

        'End If

        'If sResult.IndexOf("MPEG-4") <> -1 Then
        '    LogManual("MPEG video detected.", 1)
        '    My.Settings.MediaFormatName = "MPEG"

        '    If My.Settings.MPEGvideoPath <> vbNullString Then
        '        bmpFiletype = New Bitmap(My.Settings.MPEGvideoPath)
        '    Else
        '        'LogManual("No MPEG video icon selected", 1)
        '    End If

        'End If

        If sResult.IndexOf("DVD Video") <> -1 Then
            LogManual("DVD video detected", 1)
            My.Settings.MediaFormatName = "DVD"

            If My.Settings.DVDPath <> vbNullString Then
                bmpFiletype = New Bitmap(My.Settings.DVDPath)
            Else
                'LogManual("No DVD video icon selected", 1)
            End If
        End If

        If sResult.IndexOf("Blu-ray Video") <> -1 Then
            LogManual("Blu-ray video detected", 1)
            My.Settings.MediaFormatName = "BLURAY"

            If My.Settings.BluRayPath <> vbNullString Then
                bmpFiletype = New Bitmap(My.Settings.BluRayPath)
            Else
                'LogManual("No Blu-Ray video icon selected", 1)
            End If
        End If

        If sResult.IndexOf("Matroska") <> -1 Then
            LogManual("Matroska container detected", 1)
            My.Settings.MediaFormatName = "MKV"

            If My.Settings.MKVPath <> vbNullString Then
                bmpFiletype = New Bitmap(My.Settings.MKVPath)
            Else
                'LogManual("No MKV icon selected.", 1)
            End If
        End If

        '******* MEDIAFORMAT DETECTION (END) ********


        '******* VIDEOFORMAT DETECTION (START) ********

        If sResult.IndexOf("V_MPEG2") <> -1 Or sResult.IndexOf("MPEG Video") <> -1 Or sResult.IndexOf("MPEG-4") <> -1 Then
            LogManual("MPEG video detected.", 1)
            My.Settings.VideoFormatName = "MPEG"

            If My.Settings.MPEGvideoPath <> vbNullString Then
                bmpFiletype2 = New Bitmap(My.Settings.MPEGvideoPath)
            Else
                'LogManual("No MPEG video icon selected", 1)
            End If
        End If

        If sResult.IndexOf("264 core") <> -1 Or sResult.IndexOf("Advanced Video Codec") <> -1 Then
            LogManual("H.264 encoding detected", 1)
            My.Settings.VideoFormatName = "AVC"

            If My.Settings.H264Path <> vbNullString Then
                bmpFiletype2 = New Bitmap(My.Settings.H264Path)
            Else
                'LogManual("No H.264 icon selected.", 1)
            End If
        End If

        If sResult.IndexOf("XVID") <> -1 Then
            LogManual("Xvid detected", 1)
            My.Settings.VideoFormatName = "XVID"

            If My.Settings.XvidPath <> vbNullString Then
                bmpFiletype2 = New Bitmap(My.Settings.XvidPath)
            Else
                'LogManual("No Xvid icon selected", 1)
            End If
        End If

        If sResult.IndexOf("DivX") <> -1 Then
            LogManual("DivX detected", 1)
            My.Settings.VideoFormatName = "DIVX"

            If My.Settings.DvixPath <> vbNullString Then
                bmpFiletype2 = New Bitmap(My.Settings.DvixPath)
            Else
                'LogManual("No DIVX icon selected", 1)
            End If

        End If


        If sResult.IndexOf("VC-1") <> -1 Then
            LogManual("Windows Video detected", 1)
            My.Settings.VideoFormatName = "WMV"
        End If

        '******* VIDEOFORMAT DETECTION (END) ********


        '******* RESOLUTIONFORMAT DETECTION (START) ********

        If My.Settings.VideoHeight IsNot Nothing Then
            If My.Settings.VideoHeight < 480 Then
                LogManual("< 480p resolution detected", 1)
                My.Settings.ResolutionName = "480P"
            End If

            Select Case My.Settings.VideoHeight
                Case "480"
                    LogManual("480p resolution  detected", 1)
                    My.Settings.ResolutionName = "480P"

                Case "576"
                    LogManual("576p resolution detected", 1)
                    My.Settings.ResolutionName = "576P"
            End Select
        End If


        If sResult.IndexOf("Width                            : 1 280 pixels") <> -1 Or My.Settings.VideoHeight = 720 Then
            LogManual("720p Video detected", 1)
            My.Settings.ResolutionName = "720P"

            If My.Settings.p720 <> vbNullString Then
                bmpVideoResolution = New Bitmap(My.Settings.p720)
            Else
                'LogManual("No 720p icon selected.", 1)
            End If
        ElseIf sResult.IndexOf("Width                            : 1 920 pixels") <> -1 Then
            LogManual("1080p Video detected", 1)
            My.Settings.ResolutionName = "1080P"

            If My.Settings.p1080 <> vbNullString Then
                bmpVideoResolution = New Bitmap(My.Settings.p1080)
            Else
                'LogManual("No 1080p icon selected.", 1)
            End If
        End If

        '******* RESOLUTIONFORMAT DETECTION (END) ********


        Dim detectedAudioStreams As Integer = 0

        'detect audio

        If sResult.IndexOf("AC-3") <> -1 Then
            If sResult.IndexOf("2 channels") <> -1 Then
                LogManual("Dolby Stereo detected", 1)
                If My.Settings.SoundFormatName = Nothing Then
                    My.Settings.SoundFormatName = "DD20"
                End If

                If My.Settings.DolbyStereoPath <> vbNullString Then
                    bmpAudioFormat = New Bitmap(My.Settings.DolbyStereoPath)
                    detectedAudioStreams = 1
                Else 'LogManual("No Dolby Stereo Icon selected.", 1)
                End If

            ElseIf sResult.IndexOf("6 channels") <> -1 Then
                LogManual("Dolby Digital 5.1 detected", 1)

                If My.Settings.SoundFormatName = Nothing Then
                    My.Settings.SoundFormatName = "DD51"
                Else
                    My.Settings.SoundFormat2Name = "DD51"

                End If

                If My.Settings.DolbyPath <> vbNullString Then
                    bmpAudioFormat = New Bitmap(My.Settings.DolbyPath)
                    detectedAudioStreams = 1
                Else 'LogManual("No Dolby Digital(AC3) Icon selected.", 1)

                End If
            End If
        End If

        If sResult.IndexOf("Digital Theater Systems") <> -1 Then
            LogManual("DTS Audio detected", 1)

            If My.Settings.SoundFormatName = Nothing Then
                My.Settings.SoundFormatName = "DTS"

            ElseIf My.Settings.SoundFormat2Name = Nothing Then
                My.Settings.SoundFormat2Name = "DTS"

            End If

            If My.Settings.DTSPath <> vbNullString Then
                If detectedAudioStreams = 1 Then
                    bmpAudioFormat2 = New Bitmap(My.Settings.DTSPath)
                    detectedAudioStreams = 2
                Else
                    bmpAudioFormat = New Bitmap(My.Settings.DTSPath)
                    detectedAudioStreams = 1
                End If
            Else

                'LogManual("No DTS icon selected.", 1)
            End If
        End If

        If sResult.IndexOf("MP3") <> -1 Then
            LogManual("MP3 Audio detected", 1)

            If My.Settings.SoundFormatName = Nothing Then
                My.Settings.SoundFormatName = "MP3"
            ElseIf My.Settings.SoundFormat2Name = Nothing Then
                My.Settings.SoundFormat2Name = "MP3"
            End If

            If My.Settings.MPEGAudioPath <> vbNullString Then
                If detectedAudioStreams = 1 Then
                    bmpAudioFormat2 = New Bitmap(My.Settings.MPEGAudioPath)
                    detectedAudioStreams = 2
                Else : bmpAudioFormat = New Bitmap(My.Settings.MPEGAudioPath)
                    detectedAudioStreams = 1
                End If
            Else
                'LogManual("No MPEG audio icon selected.", 1)
            End If
        End If

        If sResult.IndexOf("AAC") <> -1 Then

            If sResult.IndexOf("2 channels") <> -1 Then
                LogManual("AAC Stereo detected", 1)

                If My.Settings.SoundFormatName = Nothing Then
                    My.Settings.SoundFormatName = "AAC20"
                ElseIf My.Settings.SoundFormat2Name = Nothing Then
                    My.Settings.SoundFormat2Name = "AAC20"
                End If

                If My.Settings.AACPath <> vbNullString Then
                    If detectedAudioStreams = 1 Then
                        bmpAudioFormat2 = New Bitmap(My.Settings.AACPath)
                        detectedAudioStreams = 2
                    Else : bmpAudioFormat = New Bitmap(My.Settings.AACPath)
                        detectedAudioStreams = 1
                    End If

                Else 'LogManual("No AAC Stereo Icon selected.", 1)

                End If

            ElseIf sResult.IndexOf("6 channels") <> -1 Then
                LogManual("AAC 5.1 detected", 1)

                If My.Settings.SoundFormatName = Nothing Then
                    My.Settings.SoundFormatName = "AAC51"
                ElseIf My.Settings.SoundFormat2Name = Nothing Then
                    My.Settings.SoundFormat2Name = "AAC51"
                End If

                If My.Settings.AAC51Path <> vbNullString Then
                    If detectedAudioStreams = 1 Then
                        bmpAudioFormat2 = New Bitmap(My.Settings.AAC51Path)
                        detectedAudioStreams = 2

                    Else : bmpAudioFormat = New Bitmap(My.Settings.AAC51Path)
                        detectedAudioStreams = 1
                    End If

                Else 'LogManual("No AAC 5.1 Icon selected.", 1)

                End If
            End If
        End If

        If sResult.IndexOf("FLAC") <> -1 Then
            LogManual("FLAC Audio detected", 1)

            If My.Settings.SoundFormatName = Nothing Then
                My.Settings.SoundFormatName = "FLAC"
            ElseIf My.Settings.SoundFormat2Name = Nothing Then
                My.Settings.SoundFormat2Name = "FLAC"
            End If

            If My.Settings.FLACPath <> vbNullString Then
                If detectedAudioStreams = 1 Then
                    bmpAudioFormat2 = New Bitmap(My.Settings.FLACPath)
                    detectedAudioStreams = 2
                Else
                    bmpAudioFormat = New Bitmap(My.Settings.FLACPath)
                    detectedAudioStreams = 1
                End If
            Else
                'LogManual("No FLAC icon selected.", 1)
            End If

        End If

        If sResult.IndexOf("Vorbis") <> -1 Then
            LogManual("OGG/Vorbis Audio detected", 1)
            If My.Settings.SoundFormatName = Nothing Then
                My.Settings.SoundFormatName = "OGG"
            ElseIf My.Settings.SoundFormat2Name = Nothing Then
                My.Settings.SoundFormat2Name = "OGG"
            End If

            If My.Settings.VorbisPath <> vbNullString Then
                If detectedAudioStreams = 1 Then
                    bmpAudioFormat2 = New Bitmap(My.Settings.VorbisPath)
                    detectedAudioStreams = 2
                Else
                    bmpAudioFormat = New Bitmap(My.Settings.VorbisPath)
                    detectedAudioStreams = 1
                End If
            Else
                'LogManual("No OGG/Vorbis icon selected.", 1)
            End If

        End If

        If My.Settings.VideoFormatName = My.Settings.MediaFormatName Then 'so it doesn't show 2 the same MPEG icons on moviesheet
            My.Settings.MediaFormatName = ""
        End If


    End Sub

    Private Sub txtDolbyDigital_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDolbyDigital.Enter
        OpenFileDialog1 = New OpenFileDialog
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtDolbyDigital.Text = OpenFileDialog1.FileName
            My.Settings.DolbyPath = txtDolbyDigital.Text
        End If
    End Sub

    Private Sub txtDTS_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDTS.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtDTS.Text = OpenFileDialog1.FileName
            My.Settings.DTSPath = txtDTS.Text
        End If
    End Sub

    Private Sub txt720_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txt720.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txt720.Text = OpenFileDialog1.FileName
            My.Settings.p720 = txt720.Text
        End If
    End Sub

    Private Sub txt1080_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txt1080.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txt1080.Text = OpenFileDialog1.FileName
            My.Settings.p1080 = txt1080.Text
        End If
    End Sub

    Private Sub btnRedo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRedo.Click

        My.Settings.VideoFormatName = ""
        My.Settings.MediaFormatName = ""
        My.Settings.SoundFormatName = ""
        My.Settings.SoundFormat2Name = ""
        My.Settings.ResolutionName = ""

        Try
            Dim s As KeyValuePair(Of String, String)
            s = lstMovies.SelectedItem
            'pnlApplyTemplate.Visible = False
            pbExistingSheet.Visible = False
            pnlCreateSheet.Visible = True
            btnRedo.Visible = False
            pbExistingSheet.Image.Dispose()
            pbExistingSheet.Image = Nothing
            '*********bit of house keeping**********
            bNotFoundOnIMDB = False
            bNotFoundOnMovieDB = False
            txtManualLog.Text = ""
            lstBackdrops.Items.Clear()
            lstPoster.Items.Clear()
            'lstPoster.DataSource = Nothing
            pbBackdropPreview.Image = Nothing
            pbPosterPreview.Image = Nothing
            aryBackdrops.Clear()
            aryPosters.Clear()
            'btnMoreFound.Visible = False
            btnGenerate.Visible = True
            btnRedoWithTemplate.Visible = False
            txtOverride.Text = ""

            bmpAudioFormat = Nothing
            bmpAudioFormat2 = Nothing
            bmpFiletype = Nothing
            bmpFiletype2 = Nothing
            bmpVideoResolution = Nothing

            Application.DoEvents()
            '**************************************
            Cursor.Current = Cursors.WaitCursor

            If My.Settings.PrimarySource = "MovieDB" Then
                Dim movieID = SearchOnTMDb_manual(s.Value)
                If movieID <> 0 Then
                    LogManual("Movie Found. ID:" & movieID.ToString, 1)
                    populateBackdrops(movieID)
                    populatePosters()
                    populateMovieInfo()
                    Application.DoEvents()
                Else
                    LogManual("Movie not found on TheMovieDB.org", 1)
                End If
            Else
                'use IMDB as primary source
                SearchOnIMDb(s.Value, 0)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
        End Try
    End Sub
    Private Function ApplyTemplate(ByVal sPath As String, ByVal bmpBackDrop As Bitmap, ByVal bmpCover As Bitmap) As Bitmap
        'Only used when 'use original'is NOT checked
        Try
            '******************
            Cursor.Current = Cursors.WaitCursor
            Dim s As New KeyValuePair(Of String, String)
            s = lstMovies.SelectedItem
            Dim MediaInfo1 As Integer, MediaInfo2 As Integer, MediaInfo3 As Integer
            MediaInfo1 = MediaInfo2 = MediaInfo3 = 0
            '************************************************************************************
            Dim doc As New XDocument
            Dim fs As New IO.FileStream(sPath, IO.FileMode.Open)
            Dim reader As New XmlTextReader(fs)
            doc = XDocument.Load(reader)
            Dim textElements = From c In doc.Elements("Template").Elements("ImageDrawTemplate").Elements("Elements").Elements("TextElement") _
                         Select c
            Dim imageElements = From c In doc.Elements("Template").Elements("ImageDrawTemplate").Elements("Elements").Elements("ImageElement") _
                         Select c
            Dim imageSettings = From c In doc.Elements("Template").Elements("ImageDrawTemplate").Elements("OutputImageSettings") _
                         Select c
            Dim templateSettings = From c In doc.Elements("Template").Elements("Settings") _
                         Select c
            Dim Canvas = From c In doc.Elements("Template").Elements("ImageDrawTemplate").Elements("Canvas") _
                         Select c

            Dim MediaFormat = From c In doc.Elements("Template").Elements("MediaFormats").Elements("MediaFormat") _
                              Select c
            Dim SoundFormat = From c In doc.Elements("Template").Elements("SoundFormats").Elements("SoundFormat") _
                              Select c
            Dim Resolution = From c In doc.Elements("Template").Elements("Resolutions").Elements("Resolution") _
                              Select c
            Dim VideoFormat = From c In doc.Elements("Template").Elements("VideoFormats").Elements("VideoFormat") _
                              Select c

            '************************************************************
            'Draw Image using template
            fs.Close()

            Dim CanvasHeight As Integer
            Dim CanvasWidth As Integer

            For Each c In Canvas
                CanvasHeight = c.Attribute("Height").Value
                CanvasWidth = c.Attribute("Width").Value
            Next

            Dim newbitmap As New Bitmap(CanvasWidth, CanvasHeight, Imaging.PixelFormat.Format32bppArgb)

            Dim dpi As Integer = CInt(imageSettings.Attributes("Dpi")(0).Value)
            Dim path = sPath.ToLower
            path = path.Replace("\template.xml", "")
            newbitmap.SetResolution(dpi, dpi)
            Dim ratingIcon As Bitmap = Nothing
            Dim sActorSeprator As Char = ""
            Dim iNumActors As Integer = 0
            Dim sGenresSeprator As Char = ""
            Dim iNumGenres As Integer = 0
            Dim sRatingIconPath As String = ""
            Dim iCountries As Integer = 0
            Dim CountriesSeparator As Char = ""
            Dim iStudios As Integer = 0
            Dim StudiosSeparator As Char = ""

            For Each setting In templateSettings
                Try
                    sActorSeprator = setting.Element("Actors").Attribute("Separator").Value
                    iNumActors = CInt(setting.Element("Actors").Attribute("MaximumValues").Value)
                    sGenresSeprator = setting.Element("Genres").Attribute("Separator").Value
                    iNumGenres = CInt(setting.Element("Genres").Attribute("MaximumValues").Value)

                    'sRatingIconPath = setting.Element("Rating").Attribute("FileName").Value.Replace("%PATH%", "")
                    sRatingIconPath = setting.Element("Rating").Attribute("FileName").Value.Replace("%PATH%", path)

                    CountriesSeparator = setting.Element("Countries").Attribute("Separator").Value
                    iCountries = CInt(setting.Element("Countries").Attribute("MaximumValues").Value)
                    StudiosSeparator = setting.Element("Studios").Attribute("Seperator").Value 'All templates use Seperator instead of Separator ! ????
                    iStudios = CInt(setting.Element("Studios").Attribute("MaximumValues").Value)
                    Application.DoEvents()

                Catch ex As Exception

                End Try
                
            Next

            For Each c1 In Resolution
                Dim Res_scan As String = ""
                Try
                    Res_scan = c1.Attribute("Name").Value

                    If My.Settings.ResolutionName.ToLower = Res_scan.ToLower Then

                        Try
                            If c1.Attribute("Image").Value.IndexOf("%PATH%") <> -1 Then
                                My.Settings.ResolutionName = c1.Attribute("Image").Value.Replace("%PATH%", path)
                                bmpVideoResolution = New Bitmap(My.Settings.ResolutionName)
                            End If
                        Catch ex As Exception

                        End Try

                    End If


                Catch ex As Exception

                End Try
            Next


            For Each c1 In SoundFormat
                Dim Sound_scan As String = ""
                Try
                    Sound_scan = c1.Attribute("Name").Value

                    If My.Settings.SoundFormatName.ToLower = Sound_scan.ToLower Then

                        Try
                            If c1.Attribute("Image").Value.IndexOf("%PATH%") <> -1 Then

                                My.Settings.SoundFormatName = c1.Attribute("Image").Value.Replace("%PATH%", path)
                                bmpAudioFormat = New Bitmap(My.Settings.SoundFormatName)

                            End If

                        Catch ex As Exception

                        End Try

                    ElseIf My.Settings.SoundFormat2Name.ToLower = Sound_scan.ToLower Then

                        Try
                            If c1.Attribute("Image").Value.IndexOf("%PATH%") <> -1 Then

                                My.Settings.SoundFormat2Name = c1.Attribute("Image").Value.Replace("%PATH%", path)
                                bmpAudioFormat2 = New Bitmap(My.Settings.SoundFormat2Name)

                            End If

                        Catch ex As Exception

                        End Try

                    End If

                Catch ex As Exception

                End Try
            Next


            For Each c1 In MediaFormat
                Dim Media_scan As String = ""
                Try
                    Media_scan = c1.Attribute("Name").Value

                    If My.Settings.MediaFormatName.ToLower = Media_scan.ToLower Then

                        Try
                            If c1.Attribute("Image").Value.IndexOf("%PATH%") <> -1 Then
                                My.Settings.MediaFormatName = c1.Attribute("Image").Value.Replace("%PATH%", path)
                                bmpFiletype = New Bitmap(My.Settings.MediaFormatName)
                            End If
                        Catch ex As Exception

                        End Try

                    End If

                Catch ex As Exception

                End Try
            Next

            For Each c1 In VideoFormat
                Dim Video_scan As String = ""
                Try
                    Video_scan = c1.Attribute("Name").Value

                    If My.Settings.VideoFormatName.ToLower = Video_scan.ToLower Then

                        Try
                            If c1.Attribute("Image").Value.IndexOf("%PATH%") <> -1 Then
                                My.Settings.VideoFormatName = c1.Attribute("Image").Value.Replace("%PATH%", path)
                                bmpFiletype2 = New Bitmap(My.Settings.VideoFormatName)
                            End If
                        Catch ex As Exception

                        End Try

                    End If

                Catch ex As Exception

                End Try
            Next


            'If IO.File.Exists(path & "\" & sRatingIconPath) Then
            If IO.File.Exists(sRatingIconPath) Then
                'ratingIcon = New Bitmap(path & "\" & sRatingIconPath)
                ratingIcon = New Bitmap(sRatingIconPath)
                My.Settings.ratingiconwidth = ratingIcon.Width
                My.Settings.ratingiconheight = ratingIcon.Height
            Else
                LogManual(sRatingIconPath & " not found !", 1)
            End If

            'Dim ratingIconwidth = ratingIcon.Width
            'Dim ratingIconheight = ratingIcon.Height
            'Dim Verhouding = ratingIconwidth / ratingIconheight

            Dim g As Graphics
            g = Graphics.FromImage(newbitmap)
            g.Clear(Color.Black)
            g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
            g.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAliasGridFit


            For Each img In imageElements
                Dim imgRect As Rectangle

                '************************
                '* Is this logical ? Make exception for Name = Background ??? 
                'If img.Attribute("Name").Value = "Background" Then
                '    imgRect = New Rectangle(0, 0, CanvasWidth, CanvasHeight)
                'Else
                imgRect = New Rectangle(img.Attribute("X").Value, img.Attribute("Y").Value, img.Attribute("Width").Value, img.Attribute("Height").Value)
                'End If
                '************************

                If img.Attribute("Source").Value = "File" Then
                    Dim newBmp As Bitmap
                    Dim sourcePath As String

                    If img.Attribute("SourceData").Value.IndexOf("%TITLEPATH%") <> -1 Then
                        sourcePath = img.Attribute("SourceData").Value.Replace("%TITLEPATH%", s.Key)

                    Else
                        sourcePath = img.Attribute("SourceData").Value.Replace("%PATH%", path)
                    End If


                    If sourcePath.Contains("%CERTIFICATION%") Then
                        sourcePath = sourcePath.Replace("%CERTIFICATION%", txtCertification.Text)
                    End If



                    If sourcePath.Contains("%STUDIOS%") Then

                        If txtStudios.Text.Contains(",") Then

                            Dim AllStudios As String = txtStudios.Text
                            Dim RestStudios As String
                            Dim FirstStudio As String

                            Dim Separator = txtStudios.Text.IndexOf(",")
                            Dim studioLenght = txtStudios.TextLength
                            Dim StudioFound = 0

                            Do While StudioFound = 0 And studioLenght > 0

                                FirstStudio = AllStudios.Substring(0, Separator)

                                If studioLenght > Separator Then
                                    RestStudios = AllStudios.Substring(Separator + 2, studioLenght - Separator - 2)
                                Else
                                    RestStudios = ""
                                End If


                                Dim sourcePath_original = sourcePath
                                sourcePath = sourcePath.Replace("%STUDIOS%", FirstStudio)

                                If IO.File.Exists(sourcePath) Then

                                    Try
                                        newBmp = New Bitmap(sourcePath)
                                    Catch ex As Exception

                                    End Try

                                    StudioFound = 1

                                Else
                                    sourcePath = sourcePath_original
                                    studioLenght = RestStudios.Length
                                    AllStudios = RestStudios
                                    Separator = AllStudios.IndexOf(",")

                                    If Separator < 0 Then
                                        Separator = studioLenght
                                    End If


                                End If

                            Loop

                            'sourcePath = sourcePath.Replace("%STUDIOS%", AllStudios)


                        Else 'No studios or only 1 studio
                            sourcePath = sourcePath.Replace("%STUDIOS%", txtStudios.Text)
                        End If

                    End If


                        If sourcePath.Contains("%COUNTRIES%") Then

                            If txtCountries.Text.Contains(",") Then 'there are more countries listed
                                'take 1st country
                                Dim FirstCountry As String
                                Dim Separator = txtCountries.Text.IndexOf(",")
                                FirstCountry = txtCountries.Text.Substring(0, Separator)
                                sourcePath = sourcePath.Replace("%COUNTRIES%", FirstCountry)
                            Else
                                sourcePath = sourcePath.Replace("%COUNTRIES%", txtCountries.Text)
                            End If
                        End If

                        If sourcePath.Contains("%BACKGROUND%") Then
                            newBmp = bmpBackDrop
                            g.DrawImage(newBmp, imgRect)
                        End If

                        If img.Attribute("SourceData").Value.IndexOf("%COVER%") <> -1 Then
                            newBmp = bmpCover
                            g.DrawImage(newBmp, imgRect)
                        End If

                        If IO.File.Exists(sourcePath) Then
                            Try
                                newBmp = New Bitmap(sourcePath)
                            Catch ex As Exception

                            End Try

                        Else
                            'Don't do anything
                        End If

                    If img.Attribute("SourceData").Value.IndexOf("BACKDROP") <> -1 Then 'Or _
                        'img.Attribute("SourceData").Value.IndexOf("BACKDROP") = -1 And img.Attribute("SourceData").Value.IndexOf("fanart") <> -1 Then
                        newBmp = bmpBackDrop
                        g.DrawImage(newBmp, imgRect)
                    End If

                    If img.Attribute("SourceData").Value.IndexOf("FANART") <> -1 And bmpFanArt1 IsNot Nothing _
                    Or img.Attribute("SourceData").Value.IndexOf("fanart") <> -1 And bmpFanArt1 IsNot Nothing _
                    Or img.Attribute("SourceData").Value.IndexOf("%FANART1%") <> -1 And bmpFanArt1 IsNot Nothing Then
                        newBmp = bmpFanArt1
                        g.DrawImage(newBmp, imgRect)
                    End If

                    If img.Attribute("SourceData").Value.IndexOf("thumb1") <> -1 And bmpFanArt2 IsNot Nothing _
                    Or img.Attribute("SourceData").Value.IndexOf("%FANART2%") <> -1 And bmpFanArt2 IsNot Nothing Then
                        newBmp = bmpFanArt2
                        g.DrawImage(newBmp, imgRect)
                    End If

                    If img.Attribute("SourceData").Value.IndexOf("thumb2") <> -1 And bmpFanArt3 IsNot Nothing _
                    Or img.Attribute("SourceData").Value.IndexOf("%FANART3%") <> -1 And bmpFanArt3 IsNot Nothing Then
                        newBmp = bmpFanArt3
                        g.DrawImage(newBmp, imgRect)
                    End If

                    If img.Attribute("Name") IsNot Nothing Then
                        Select Case img.Attribute("Name").Value
                            Case "ResolutionINFO"
                                If bmpVideoResolution IsNot Nothing Then
                                    newBmp = bmpVideoResolution
                                Else
                                    newBmp = Nothing
                                End If
                                'LogManual("VideoStream found", 1)
                            Case "AudioCodecINFO"
                                If bmpAudioFormat IsNot Nothing Then
                                    newBmp = bmpAudioFormat
                                Else
                                    newBmp = Nothing
                                End If
                                'LogManual("AudioStream1 found", 1)
                            Case "AudioCodecINFO2"
                                If bmpAudioFormat2 IsNot Nothing Then
                                    newBmp = bmpAudioFormat2
                                Else
                                    newBmp = Nothing
                                End If
                                'LogManual("AudioStream2 found", 1)
                            Case "Filetype"
                                If bmpFiletype IsNot Nothing Then
                                    newBmp = bmpFiletype
                                Else
                                    newBmp = Nothing
                                End If
                            Case Else
                                'LogManual("Nothing to be done for this img.Attribute..", 1)
                        End Select
                    End If

                    'Put image on Template (if available at location specified in template)
                    If newBmp IsNot Nothing And IO.File.Exists(sourcePath) Then
                        g.DrawImage(newBmp, imgRect)
                    Else
                        'LogManual("Your template refers to " & sourcePath & " which is not found !", 1)

                    End If

                Else
                    If img.Attribute("SourceData").Value.Equals("%RATINGSTARS%") Then
                        'determine image width and height of ratingstar image
                        Dim starheight As String = img.Attribute("Height").Value
                        Dim starwidth As String = img.Attribute("Width").Value

                        'Dim newRating As New Bitmap(CInt(starwidth), CInt(starheight))
                        Dim newRating As New Bitmap(5 * (My.Settings.ratingiconwidth), My.Settings.ratingiconheight)

                        'Dim newRating As New Bitmap(120, 24)
                        Dim g1 As Graphics
                        g1 = Graphics.FromImage(newRating)

                        'Dim imgRect1 As New Rectangle(0, 0, 24, 24)
                        'Dim imgRect2 As New Rectangle(24, 0, 24, 24)
                        'Dim imgRect3 As New Rectangle(48, 0, 24, 24)
                        'Dim imgRect4 As New Rectangle(72, 0, 24, 24)
                        'Dim imgRect5 As New Rectangle(96, 0, 24, 24)

                        Dim imgRect1 As New Rectangle(0, 0, My.Settings.ratingiconwidth, My.Settings.ratingiconheight)
                        Dim imgRect2 As New Rectangle(1 * My.Settings.ratingiconwidth, 0, My.Settings.ratingiconwidth, My.Settings.ratingiconheight)
                        Dim imgRect3 As New Rectangle(2 * My.Settings.ratingiconwidth, 0, My.Settings.ratingiconwidth, My.Settings.ratingiconheight)
                        Dim imgRect4 As New Rectangle(3 * My.Settings.ratingiconwidth, 0, My.Settings.ratingiconwidth, My.Settings.ratingiconheight)
                        Dim imgRect5 As New Rectangle(4 * My.Settings.ratingiconwidth, 0, My.Settings.ratingiconwidth, My.Settings.ratingiconheight)

                        g1.DrawImage(ratingIcon, imgRect1)
                        g1.DrawImage(ratingIcon, imgRect2)
                        g1.DrawImage(ratingIcon, imgRect3)
                        g1.DrawImage(ratingIcon, imgRect4)
                        g1.DrawImage(ratingIcon, imgRect5)

                        'Checks system Decimal Separator
                        Dim DecimalSeparator As String
                        DecimalSeparator = Mid$(1 / 2, 2, 1)

                        'Replace "." for a "," before draw the stars
                        Dim Temp As String
                        Temp = txtRating.Text
                        If DecimalSeparator = "," Then
                            Temp = Temp.Replace(".", ",")
                        ElseIf DecimalSeparator = "." Then
                            Temp = Temp.Replace(",", ".")
                        End If
                        Dim rating = CDbl(Temp.Split("/")(0))

                        'Dim pixelsToShow = (rating * 10) * 1.2
                        Dim pixelsToShow = (rating / 10) * (5 * My.Settings.ratingiconwidth)

                        Dim newRect = imgRect
                        'newRect.Width = pixelsToShow * Verhouding
                        newRect.Width = pixelsToShow
                        newRect.Height = My.Settings.ratingiconheight

                        'g1.Clip = New Region(New Rectangle(10, 10, 20, newRect.Height))

                        g.DrawImage(newRating, newRect, New Rectangle(0, 0, newRect.Width, newRect.Height), GraphicsUnit.Pixel)

                    End If

                    Dim newBmp As Bitmap

                    If img.Attribute("SourceData").Value = "%COVER%" Then
                        newBmp = bmpCover
                        g.DrawImage(newBmp, imgRect)
                    End If

                    If img.Attribute("SourceData").Value = "%BACKGROUND%" Then
                        newBmp = bmpBackDrop
                        g.DrawImage(newBmp, imgRect)
                    End If

                    If img.Attribute("SourceData").Value = "%RESOLUTION%" Then
                        If bmpVideoResolution IsNot Nothing Then
                            newBmp = bmpVideoResolution
                            g.DrawImage(newBmp, imgRect)
                        Else
                            newBmp = Nothing
                        End If
                    End If

                    If img.Attribute("SourceData").Value = "%MEDIAFORMAT%" Then
                        If bmpFiletype IsNot Nothing Then
                            newBmp = bmpFiletype
                            g.DrawImage(newBmp, imgRect)
                        Else
                            newBmp = Nothing
                        End If
                    End If

                    If img.Attribute("SourceData").Value = "%VIDEOFORMAT%" Then
                        If bmpFiletype2 IsNot Nothing Then
                            newBmp = bmpFiletype2
                            g.DrawImage(newBmp, imgRect)
                        Else
                            newBmp = Nothing
                        End If
                    End If

                    If img.Attribute("SourceData").Value = "%SOUNDFORMAT%" Then
                        If bmpAudioFormat IsNot Nothing Then
                            newBmp = bmpAudioFormat
                            g.DrawImage(newBmp, imgRect)
                        Else
                            newBmp = Nothing

                        End If
                    End If

                    If img.Attribute("SourceData").Value = "%SOUNDFORMAT2%" Then
                        If bmpAudioFormat2 IsNot Nothing Then
                            newBmp = bmpAudioFormat2
                            g.DrawImage(newBmp, imgRect)
                        Else
                            newBmp = Nothing
                        End If
                    End If
                End If

            Next



            'Checking template for TextElements starts here:

            For Each txt In textElements
                Dim sText As String = ""

                Dim sFontInfo() As String = txt.Attribute("Font").Value.Split(",")

                'now check if fontsize contains decimal separator
                If sFontInfo(1).Contains(".") Then
                    sFontInfo(1) = sFontInfo(1).Replace(".", "")
                    sFontInfo(1) = sFontInfo(1) / 10
                ElseIf sFontInfo(1).Contains(",") Then
                    sFontInfo(1) = sFontInfo(1).Replace(",", "")
                    sFontInfo(1) = sFontInfo(1) / 10
                End If

                Dim size = CInt(sFontInfo(1))
                Dim iStyle As Integer = 0
                If sFontInfo.Length = 9 Then

                    If sFontInfo(2) = "True" Then
                        iStyle = FontStyle.Bold
                    ElseIf sFontInfo(3) = "True" Then
                        iStyle = FontStyle.Italic
                    ElseIf sFontInfo(4) = "True" Then
                        iStyle = FontStyle.Underline
                    ElseIf sFontInfo(5) = "True" Then
                        iStyle = FontStyle.Strikeout
                    End If
                End If

                Dim sf As New StringFormat
                If txt.Attribute("TextAlignment").Value.IndexOf("Center") <> -1 Then
                    sf.Alignment = StringAlignment.Center
                ElseIf txt.Attribute("TextAlignment").Value.IndexOf("Left") <> -1 Then
                    sf.Alignment = StringAlignment.Near
                ElseIf txt.Attribute("TextAlignment").Value.IndexOf("Right") <> -1 Then
                    sf.Alignment = StringAlignment.Far
                End If


                'TEST START

                Dim RgTest As New ContentAlignment
                If txt.Attribute("TextAlignment") = "MiddleRight" Then
                    RgTest = MiddleRight
                ElseIf txt.Attribute("TextAlignment") = "MiddleLeft" Then
                    RgTest = MiddleLeft
                ElseIf txt.Attribute("TextAlignment") = "MiddleCenter" Then
                    RgTest = MiddleCenter
                ElseIf txt.Attribute("TextAlignment") = "BottomCenter" Then
                    RgTest = BottomCenter
                ElseIf txt.Attribute("TextAlignment") = "BottomLeft" Then
                    RgTest = BottomLeft
                ElseIf txt.Attribute("TextAlignment") = "BottomRight" Then
                    RgTest = BottomRight
                ElseIf txt.Attribute("TextAlignment") = "TopCenter" Then
                    RgTest = TopCenter
                ElseIf txt.Attribute("TextAlignment") = "TopLeft" Then
                    RgTest = TopLeft
                ElseIf txt.Attribute("TextAlignment") = "TopRight" Then
                    RgTest = TopRight
                End If

                'TEST END


                Dim f As New Font(sFontInfo(0), size, iStyle, GraphicsUnit.Point)
                Dim txtRect As New Rectangle(txt.Attribute("X").Value, txt.Attribute("Y").Value, txt.Attribute("Width").Value, txt.Attribute("Height").Value)

                sText = txt.Attribute("Text").Value

                If txt.Attribute("Text").Value.IndexOf("%PLOT%") <> -1 Then
                    sText = txt.Attribute("Text").Value.Replace("%PLOT%", txtSummary.Text)
                End If

                If txt.Attribute("Text").Value.IndexOf("%TITLE%") <> -1 Then
                    If sText = vbNullString Then
                        sText = txt.Attribute("Text").Value.Replace("%TITLE%", txtTitle.Text)
                    Else
                        sText = sText.Replace("%TITLE%", txtTitle.Text)
                    End If
                End If

                If txt.Attribute("Text").Value.IndexOf("%YEAR%") <> -1 Then
                    If sText = vbNullString Then
                        sText = txt.Attribute("Text").Value.Replace("%YEAR%", txtYear.Text)
                    Else
                        sText = sText.Replace("%YEAR%", txtYear.Text)
                    End If

                End If

                If txt.Attribute("Text").Value.IndexOf("%ACTORS%") <> -1 Then
                    Dim sActorsToShow As New System.Text.StringBuilder

                    Dim sActors = txtActors.Text.Split(",")
                    Dim iLimit As Integer = 0
                    If sActors.Length > iNumActors Then
                        iLimit = iNumActors
                    Else
                        iLimit = sActors.Length
                    End If

                    For i As Integer = 0 To iLimit - 1 Step 1
                        If sActors(i).Trim <> vbNullString Then
                            If i = 0 Then
                                sActorsToShow.Append(sActors(i))
                            Else
                                sActorsToShow.Append(sActorSeprator & sActors(i))
                            End If
                        End If
                    Next
                    If sText = vbNullString Then
                        sText = txt.Attribute("Text").Value.Replace("%ACTORS%", sActorsToShow.ToString)
                    Else
                        sText = sText.Replace("%ACTORS%", sActorsToShow.ToString)
                    End If

                End If


                If txt.Attribute("Text").Value.IndexOf("%GENRES%") <> -1 Then
                    Dim sGenresToShow As New System.Text.StringBuilder

                    Dim sGenres = txtGenres.Text.Split(",")
                    Dim iLimit As Integer = 0
                    If sGenres.Length > iNumGenres Then
                        iLimit = iNumGenres
                    Else
                        iLimit = sGenres.Length
                    End If
                    For i As Integer = 0 To iLimit - 1 Step 1
                        If sGenres(i).Trim <> vbNullString Then
                            If i = 0 Then
                                sGenresToShow.Append(sGenres(i))
                            Else
                                sGenresToShow.Append(sGenresSeprator & sGenres(i))
                            End If
                        End If
                    Next
                    If sText = vbNullString Then
                        sText = txt.Attribute("Text").Value.Replace("%GENRES%", sGenresToShow.ToString)
                    Else
                        sText = sText.Replace("%GENRES%", sGenresToShow.ToString)
                    End If

                End If

                If txt.Attribute("Text").Value.IndexOf("%DIRECTORS%") <> -1 Then

                    If sText = vbNullString Then
                        sText = txt.Attribute("Text").Value.Replace("%DIRECTORS%", txtDirectors.Text)
                    Else
                        sText = sText.Replace("%DIRECTORS%", txtDirectors.Text)
                    End If

                End If

                If txt.Attribute("Text").Value.IndexOf("%RUNTIME%") <> -1 Then
                    sText = sText.Replace("%RUNTIME%", txtRunTime.Text)
                End If

                If txt.Attribute("Text").Value.IndexOf("%DURATION%") <> -1 Then
                    sText = sText.Replace("%DURATION%", txtRunTime.Text)
                End If

                If txt.Attribute("Text").Value.IndexOf("%DURATIONSEC%") <> -1 Then
                    sText = sText.Replace("%DURATIONSEC%", txtRunTime.Text * 60)
                End If

                If txt.Attribute("Text").Value.IndexOf("%DURATIONTEXT%") <> -1 Then
                    Dim hours As Integer
                    Dim minutes As Integer

                    Dim A = txtRunTime.Text
                    Dim B = 60
                    Dim C = 0

                    Do While A >= B
                        A = A - B
                        C = C + 1
                    Loop

                    hours = C
                    minutes = A

                    sText = sText.Replace("%DURATIONTEXT%", C & "h " & A & "m")

                End If

                If txt.Attribute("Text").Value.IndexOf("%RATING%") <> -1 Then
                    sText = txt.Attribute("Text").Value.Replace("%RATING%", txtRating.Text)
                End If

                If txt.Attribute("Text").Value.IndexOf("%RATINGPERCENT%") <> -1 Then
                    Dim Temp As String
                    Dim DecimalSeparator As String
                    DecimalSeparator = Mid$(1 / 2, 2, 1)
                    Temp = txtRating.Text
                    If DecimalSeparator = "," Then
                        Temp = Temp.Replace(".", ",")
                        Dim rating1 = CDbl(Temp.Split("/")(0))
                        sText = txt.Attribute("Text").Value.Replace("%RATINGPERCENT%", rating1 * 10)
                    ElseIf DecimalSeparator = "." Then
                        Temp = Temp.Replace(",", ".")
                        Dim rating = CDbl(Temp.Split("/")(0))
                        sText = txt.Attribute("Text").Value.Replace("%RATINGPERCENT%", rating)
                    End If

                End If


                If txt.Attribute("Text").Value.IndexOf("%ORIGINALTITLE%") <> -1 Then
                    sText = txt.Attribute("Text").Value.Replace("%ORIGINALTITLE%", txtOriginalTitle.Text)
                End If

                If txt.Attribute("Text").Value.IndexOf("%TAGLINE%") <> -1 Then
                    sText = sText.Replace("%TAGLINE%", txtTagline.Text)
                End If


                If txt.Attribute("Text").Value.IndexOf("%COUNTRIES%") <> -1 Then

                    Dim sCountriesToShow As New System.Text.StringBuilder

                    Dim sCountries = txtCountries.Text.Split(",")
                    Dim iLimit As Integer = 0
                    If sCountries.Length > iCountries Then
                        iLimit = iCountries
                    Else
                        iLimit = sCountries.Length
                    End If
                    For i As Integer = 0 To iLimit - 1 Step 1
                        If sCountries(i).Trim <> vbNullString Then
                            If i = 0 Then
                                sCountriesToShow.Append(sCountries(i))
                            Else
                                sCountriesToShow.Append(CountriesSeparator & sCountries(i))
                            End If
                        End If
                    Next
                    If sText = vbNullString Then
                        sText = txt.Attribute("Text").Value.Replace("%COUNTRIES%", sCountriesToShow.ToString)
                    Else
                        sText = sText.Replace("%COUNTRIES%", sCountriesToShow.ToString)
                    End If


                End If

                If txt.Attribute("Text").Value.IndexOf("%STUDIOS%") <> -1 Then

                    Dim sStudiosToShow As New System.Text.StringBuilder

                    Dim sStudios = txtStudios.Text.Split(",")
                    Dim iLimit As Integer = 0
                    If sStudios.Length > iCountries Then
                        iLimit = iCountries
                    Else
                        iLimit = sStudios.Length
                    End If
                    For i As Integer = 0 To iLimit - 1 Step 1
                        If sStudios(i).Trim <> vbNullString Then
                            If i = 0 Then
                                sStudiosToShow.Append(sStudios(i))
                            Else
                                sStudiosToShow.Append(StudiosSeparator & sStudios(i))
                            End If
                        End If
                    Next
                    If sText = vbNullString Then
                        sText = txt.Attribute("Text").Value.Replace("%STUDIOS%", sStudiosToShow.ToString)
                    Else
                        sText = sText.Replace("%STUDIOS%", sStudiosToShow.ToString)
                    End If

                End If


                If txt.Attribute("Text").Value.IndexOf("%CERTIFICATION%") <> -1 Then
                    sText = txt.Attribute("Text").Value.Replace("%CERTIFICATION%", txtCertification.Text)
                End If

                If txt.Attribute("Text").Value.IndexOf("%MPAA%") <> -1 Then
                    If txtCertification.Text = "PG-13" Then
                        sText = txt.Attribute("Text").Value.Replace("%MPAA%", "Parents strongly cautioned. Some material may be inappropriate for children under 13.")
                    ElseIf txtCertification.Text = "PG" Then
                        sText = txt.Attribute("Text").Value.Replace("%MPAA%", "Parental guidance suggested. Some material may not be suitable for children.")
                    ElseIf txtCertification.Text = "G" Then
                        sText = txt.Attribute("Text").Value.Replace("%MPAA%", "General audiences. All ages admitted.")
                    ElseIf txtCertification.Text = "R" Then
                        sText = txt.Attribute("Text").Value.Replace("%MPAA%", "Restricted. Children under 17 require accompanying parent or adult guardian.")
                    ElseIf txtCertification.Text = "NC-17" Then
                        sText = txt.Attribute("Text").Value.Replace("%MPAA%", "No one 17 and under admitted.")
                    Else
                        sText = txt.Attribute("Text").Value.Replace("%MPAA%", " ")
                    End If
                End If

                If txt.Attribute("Text").Value.IndexOf("%FRAMERATETEXT%") <> -1 Then
                    sText = sText.Replace("%FRAMERATETEXT%", My.Settings.Framerate)
                End If

                If txt.Attribute("Text").Value.IndexOf("%ASPECTRATIOTEXT%") <> -1 Then
                    sText = sText.Replace("%ASPECTRATIOTEXT%", My.Settings.DisplayAspectRatio)
                End If

                If txt.Attribute("Text").Value.IndexOf("%FILESIZETEXT%") <> -1 Then
                    sText = sText.Replace("%FILESIZETEXT%", My.Settings.Filesize)
                End If

                If txt.Attribute("Text").Value.IndexOf("%VIDEORESOLUTION%") <> -1 Then
                    sText = sText.Replace("%VIDEORESOLUTION%", My.Settings.VideoWidth & "x" & My.Settings.VideoHeight)
                End If


                If sText.Contains("{TITLECASE}") Then
                    sText = sText.Replace("{TITLECASE}", "")
                    Dim Culture As CultureInfo = Thread.CurrentThread.CurrentCulture
                    Dim Culturetxt As TextInfo = Culture.TextInfo()
                    sText = Culturetxt.ToTitleCase(sText)
                End If

                If sText.Contains("{UPPER}") Then
                    sText = sText.Replace("{UPPER}", "")
                    Dim Culture As CultureInfo = Thread.CurrentThread.CurrentCulture
                    Dim Culturetxt As TextInfo = Culture.TextInfo()
                    sText = Culturetxt.ToUpper(sText)
                End If

                If sText.Contains("{LOWER}") Then
                    sText = sText.Replace("{LOWER}", "")
                    Dim Culture As CultureInfo = Thread.CurrentThread.CurrentCulture
                    Dim Culturetxt As TextInfo = Culture.TextInfo()
                    sText = Culturetxt.ToLower(sText)
                End If

                'trim  string till it fits on one line
                If txt.Attribute("Multiline").Value.Equals("False") And txt.Attribute("AutoSize").Value.Equals("False") Then
                    Dim bApplyEndString As Boolean = False
                    Dim i As Integer = 1
                    If sText <> vbNullString And txtRect.Width <> 0 Then
                        Dim sizeTrimForDots = TextRenderer.MeasureText("...", f)
                        'allow for a little bit bigger
                        If TextRenderer.MeasureText(sText, f).Width > txtRect.Width + 5 Then
                            While TextRenderer.MeasureText(sText, f, New Size(txtRect.Width, txtRect.Height)).Width > txtRect.Width - sizeTrimForDots.Width
                                sText = sText.Substring(0, sText.Length - i)
                                bApplyEndString = True
                            End While
                        End If
                        If bApplyEndString Then
                            sText = sText & "..."
                        End If
                        If TextRenderer.MeasureText(sText, f).Height > txtRect.Height + 5 = False Then

                            txtRect.Height = TextRenderer.MeasureText(sText, f).Height
                        End If
                    End If
                ElseIf txt.Attribute("AutoSize").Value.Equals("True") Then
                    txtRect.Width = 0
                    txtRect.Height = 0
                End If

                Dim myBrush As New SolidBrush(ColorTranslator.FromOle(CInt(txt.Attribute("ForeColor").Value)))
                Dim myBrush2 As New SolidBrush(ColorTranslator.FromOle(CInt(txt.Attribute("StrokeColor").Value)))
                'Strokewidth needs determining too?!

                'bug in tvixie maps wrong color values to RGB pallette.
                Dim correctColor As Color = Color.FromArgb(255, myBrush.Color.B, myBrush.Color.G, myBrush.Color.R)
                Dim myBrush2Color As Color = Color.FromArgb(255, myBrush2.Color.B, myBrush2.Color.G, myBrush2.Color.R)

                myBrush.Color = correctColor
                g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
                g.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAliasGridFit
                g.DrawString(sText, f, myBrush, txtRect, sf)

            Next
            Application.DoEvents()
            Return newbitmap
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Return Nothing
        End Try
    End Function

    Private Sub btnAddTemplate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddTemplate.Click
        Try
            Dim sTemplatePath = txtSelectTemplate.Text
            Dim sTemplateName As String = ""
            'get template name from path
            Dim sFolders = sTemplatePath.Split("\")
            sTemplateName = sFolders(sFolders.Length - 2)

            Dim newLstViewItem As New ListViewItem
            newLstViewItem.Text = sTemplateName
            newLstViewItem.SubItems.Add(sTemplatePath)
            lstTemplates.Items.Add(newLstViewItem)
            saveTemplates()
            cboTemplates.DataSource = Nothing
            cboTemplates.DataSource = lstTemplates.Items
            cboTemplates.DisplayMember = "Text"
            cboTemplates.SelectedIndex = getDefualtLocation()
            cboApplyNewTemplate.DataSource = Nothing

            cboApplyNewTemplate.DataSource = lstTemplates.Items
            cboApplyNewTemplate.DisplayMember = "Text"
            cboApplyNewTemplate.SelectedIndex = getDefualtLocation()
            previewNewTemplate(sTemplatePath)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub previewNewTemplate(ByVal sTemplatePath As String)
        Try

            Dim s As New KeyValuePair(Of String, String)(IO.Path.GetDirectoryName(Application.ExecutablePath) & "\Sample\", "")

            If IO.File.Exists(s.Key & "\Movie_Info.xml") Then
                LoadXML(s.Key & "\Movie_Info.xml")
                Dim bmpBackdropLocal As New Bitmap(s.Key & "\backdrop.jpg")
                Dim bmpCoverLocal As New Bitmap(s.Key & "\cover.jpg")
                If IO.File.Exists(s.Key & "\fanart1.jpg") Then
                    bmpFanArt1 = New Bitmap(s.Key & "\fanart1.jpg")
                Else
                    bmpFanArt1 = Nothing
                End If
                If IO.File.Exists(s.Key & "\fanart2.jpg") Then
                    bmpFanArt2 = New Bitmap(s.Key & "\fanart2.jpg")
                Else
                    bmpFanArt2 = Nothing
                End If
                If IO.File.Exists(s.Key & "\fanart3.jpg") Then
                    bmpFanArt3 = New Bitmap(s.Key & "\fanart3.jpg")
                Else
                    bmpFanArt3 = Nothing
                End If
                bmpVideoResolution = My.Resources.Images.HD_1080P_1
                bmpAudioFormat = My.Resources.Images.DTS_white
                createdImage = ApplyTemplate(sTemplatePath, bmpBackdropLocal, bmpCoverLocal)
                pbPreview.Image = createdImage
                pbPreview.SizeMode = PictureBoxSizeMode.Zoom
                createdImage.Save(sTemplatePath.Replace("Template.xml", "") & "wdtv_preview.jpg")
                Application.DoEvents()
                bmpVideoResolution = Nothing
                bmpAudioFormat = Nothing
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub btnMakeDefault_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMakeDefault.Click
        Try
            For Each item As ListViewItem In lstTemplates.Items
                item.BackColor = Color.White
                item.SubItems(1).Text = item.SubItems(1).Text.Replace("*", "")
            Next
            lstTemplates.Items(lstTemplates.SelectedIndices(0)).BackColor = Color.SkyBlue
            sDefaultTemplatePath = lstTemplates.Items(lstTemplates.SelectedIndices(0)).SubItems(1).Text
            lstTemplates.Items(lstTemplates.SelectedIndices(0)).SubItems(1).Text = "*" & lstTemplates.Items(lstTemplates.SelectedIndices(0)).SubItems(1).Text

            saveTemplates()
            cboTemplates.SelectedIndex = getDefualtLocation()
            cboApplyNewTemplate.SelectedIndex = getDefualtLocation()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub saveTemplates()
        Try
            Dim sTemplates As String = ""
            For Each template As ListViewItem In lstTemplates.Items
                sTemplates = sTemplates & template.SubItems(1).Text & ";"
            Next
            My.Settings.SavedTemplates = sTemplates
            My.Settings.Save()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Function getDefualtLocation()
        Try
            Dim q = (From lvi As ListViewItem In lstTemplates.Items _
                    Where lvi.BackColor = Color.SkyBlue _
                    Select lvi.Index).FirstOrDefault
            Return q
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Function
    Private Sub loadSavedTemplates()
        Try
            'now load the templates storeds in the settings file
            Dim sTemplates = My.Settings.SavedTemplates.Split(";")
            For Each sTemplate In sTemplates
                If sTemplate <> vbNullString Then
                    Dim sTemplateName As String = ""
                    'get template name from path
                    Dim sFolders = sTemplate.Split("\")
                    sTemplateName = sFolders(sFolders.Length - 2)

                    Dim newItem As New ListViewItem
                    newItem.Text = sTemplateName
                    newItem.SubItems.Add(sTemplate)
                    If sTemplate.IndexOf("*") <> -1 Then
                        newItem.BackColor = Color.SkyBlue
                        sDefaultTemplatePath = sTemplate.Replace("*", "")
                    End If
                    lstTemplates.Items.Add(newItem)
                End If
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemoveTemplate.Click
        Try
            lstTemplates.Items.RemoveAt(lstTemplates.SelectedIndices(0))
            saveTemplates()
            cboTemplates.DataSource = Nothing
            cboTemplates.DataSource = lstTemplates.Items
            cboTemplates.DisplayMember = "Text"
            cboTemplates.SelectedIndex = getDefualtLocation()
            cboApplyNewTemplate.DataSource = Nothing

            cboApplyNewTemplate.DataSource = lstTemplates.Items
            cboApplyNewTemplate.DisplayMember = "Text"
            cboApplyNewTemplate.SelectedIndex = getDefualtLocation()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub chkUseOriginal_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkUseOriginal.CheckedChanged
        If chkUseOriginal.Checked = True Then
            lstTemplates.Enabled = False
            cboTemplates.Visible = False
            lblTemplates.Visible = False

        Else
            lblTemplates.Visible = True
            lstTemplates.Enabled = True
            cboTemplates.Visible = True

        End If
        My.Settings.UseOriginal = chkUseOriginal.Checked
        My.Settings.Save()
    End Sub

    Private Sub LoadXML(ByVal sXMLPath As String)
        Try
            Dim doc As New XDocument
            Dim reader As New XmlTextReader(sXMLPath)
            doc = XDocument.Load(reader)
            Dim q = From c In doc.Elements("Movie") _
               Select c
            Dim firstOBJ = q.ElementAt(0)
            'populate new currentTitle object
            currentTitle = New IMDbTitle
            With currentTitle
                txtTitle.Text = firstOBJ.Attribute("Title").Value.ToString
                txtYear.Text = firstOBJ.Attribute("Year").Value.ToString
                txtSummary.Text = firstOBJ.Attribute("Plot").Value.ToString
                txtRunTime.Text = firstOBJ.Attribute("Runtime").Value.ToString
                txtRating.Text = firstOBJ.Attribute("Rating").Value.ToString()

                If firstOBJ.Attribute("Tagline") IsNot Nothing Then
                    txtTagline.Text = firstOBJ.Attribute("Tagline").Value.ToString
                End If

                If firstOBJ.Attribute("Actors") IsNot Nothing Then
                    txtActors.Text = firstOBJ.Attribute("Actors").Value.ToString
                End If

                If firstOBJ.Attribute("Directors") IsNot Nothing Then
                    txtDirectors.Text = firstOBJ.Attribute("Directors").Value.ToString
                End If
                If firstOBJ.Attribute("Genres") IsNot Nothing Then
                    txtGenres.Text = firstOBJ.Attribute("Genres").Value.ToString
                End If
                If firstOBJ.Attribute("Certification") IsNot Nothing Then
                    txtCertification.Text = firstOBJ.Attribute("Certification").Value.ToString
                End If
                If firstOBJ.Attribute("OriginalTitle") IsNot Nothing Then
                    txtOriginalTitle.Text = firstOBJ.Attribute("OriginalTitle").Value.ToString
                End If
                If firstOBJ.Attribute("Countries") IsNot Nothing Then
                    txtCountries.Text = firstOBJ.Attribute("Countries").Value.ToString
                End If
                If firstOBJ.Attribute("Studios") IsNot Nothing Then
                    txtStudios.Text = firstOBJ.Attribute("Studios").Value.ToString
                End If

            End With
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub btnRedoWithTemplate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRedoWithTemplate.Click
        Try
            'load cached info
            Dim s As KeyValuePair(Of String, String)
            s = lstMovies.SelectedItem
            'first check and show any existing moviesheet
            If IO.File.Exists(s.Key & "\Movie_Info.xml") Then
                LoadXML(s.Key & "\Movie_Info.xml")
                Dim bmpBackdropLocal As New Bitmap(s.Key & "\backdrop.jpg")
                Dim bmpCoverLocal As New Bitmap(s.Key & "\cover.jpg")
                If IO.File.Exists(s.Key & "\fanart1.jpg") Then
                    bmpFanArt1 = New Bitmap(s.Key & "\fanart1.jpg")
                Else
                    bmpFanArt1 = Nothing
                End If
                If IO.File.Exists(s.Key & "\fanart2.jpg") Then
                    bmpFanArt2 = New Bitmap(s.Key & "\fanart2.jpg")
                Else
                    bmpFanArt2 = Nothing
                End If
                If IO.File.Exists(s.Key & "\fanart3.jpg") Then
                    bmpFanArt3 = New Bitmap(s.Key & "\fanart3.jpg")
                Else
                    bmpFanArt3 = Nothing
                End If
                If bmpFanArt1 IsNot Nothing And bmpFanArt2 IsNot Nothing And bmpFanArt3 IsNot Nothing Then
                    pbExistingSheet.Image.Dispose()
                End If
                pbExistingSheet.Image = Nothing
                If My.Settings.AnalyseMKVs And cbManuallyInput.Checked = False Then
                    AnalyseMovie(s)
                    'User wants to manually input
                Else
                    ManuallyCreateVideoAudioFormat()
                End If
                'get path of selected template
                Dim overridePath = (From lvi As ListViewItem In lstTemplates.Items _
                Where (lvi.Text = cboApplyNewTemplate.Text) _
                       Select lvi.SubItems(1).Text).FirstOrDefault
                overridePath = overridePath.Replace("*", "")
                Dim sTitle As String = txtTitle.Text
                Dim sSummary As String = txtSummary.Text
                Dim sRating As String = txtRating.Text.ToString
                Dim sRunTime As String = txtRunTime.Text.ToString
                Dim bmpFolderImage As New Bitmap(My.Settings.CoverWidth, My.Settings.CoverHeight)

                Dim g = Graphics.FromImage(bmpFolderImage)
                Dim coverRect As New Rectangle(0, 0, My.Settings.CoverWidth, My.Settings.CoverHeight)

                g.DrawImage(bmpCoverLocal, coverRect)

                'createdImage = ApplyTemplate(overridePath, bmpBackdropLocal, bmpCoverLocal)

                If chkUseOriginal.Checked = False Then
                    'createdImage = ApplyTemplate(sDefaultTemplatePath, bmpBackdropLocal, bmpCoverLocal)
                    createdImage = ApplyTemplate(overridePath, bmpBackdropLocal, bmpCoverLocal)
                Else
                    createdImage = generateImage(bmpCoverLocal, bmpBackdropLocal, sTitle, sSummary, sRunTime, sRating)
                End If
                loadedBitmap.Dispose()
                pbExistingSheet.Image = Nothing
                createdImage.Save(s.Key & "\" & My.Settings.MovieSheetName, Imaging.ImageFormat.Jpeg)
                'GenerateXML(s.Key)
                Application.DoEvents()
                pbExistingSheet.Image = createdImage
                lstMovies_SelectedIndexChanged(sender, e)
            Else
                MessageBox.Show("There is no cached information stored on this movie. Press 'ReDo' and generate a new movie sheet. This will create a cache of data for this movie")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    '    Private Sub btnEditMovieInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '        If btnEditMovieInfo.Text = "EDIT" Then
    'pnlMovieInfo.Visible = True
    'btnEditMovieInfo.Text = "HIDE"
    'pnlMovieInfo.BringToFront()
    'pbExistingSheet.Size = New Size(pbExistingSheet.Size.Width / 2, pbExistingSheet.Size.Width / 2)
    '            pbExistingSheet.Size = New Size(816, 459)
    '       Else
    'pnlMovieInfo.Visible = False
    '            btnEditMovieInfo.Text = "EDIT"
    'pbExistingSheet.Size = New Size(960, 540)
    '           pbExistingSheet.Size = New Size(816, 459)

    '      End If
    ' End Sub

    Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
        Try
            OpenFileDialog1 = New OpenFileDialog
            OpenFileDialog1.Filter = "XML Files (*.xml)|*.xml;"

            Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
            thFolderSelection.SetApartmentState(ApartmentState.STA)
            thFolderSelection.IsBackground = True
            thFolderSelection.Start()
            thFolderSelection.Join()


            If OpenFileDialog1.FileName <> vbNullString Then
                txtSelectTemplate.Text = OpenFileDialog1.FileName
            End If
            OpenFileDialog1.Filter = ""
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub mnuFanArt1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuFanArt1.Click
        Try
            If mnuFanArt1.Checked = False Then
                lstBackdrops.SelectedItems(0).BackColor = Color.Blue
                mnuFanArt1.Checked = True
                Dim s As KeyValuePair(Of Bitmap, String) = lstBackdrops.SelectedItems(0).Tag
                bmpFanArt1 = New Bitmap(s.Key)
            ElseIf lstBackdrops.SelectedItems(0).BackColor = Color.Blue Then
                mnuFanArt1.Checked = False
                lstBackdrops.SelectedItems(0).BackColor = Color.White
            Else
                For Each lvi As ListViewItem In lstBackdrops.Items
                    If lvi.BackColor = Color.Blue Then
                        lvi.BackColor = Color.White
                    End If
                Next
                lstBackdrops.SelectedItems(0).BackColor = Color.Blue
                Dim s As KeyValuePair(Of Bitmap, String) = lstBackdrops.SelectedItems(0).Tag
                bmpFanArt1 = New Bitmap(s.Key)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub ContextMenuStrip1_Opening(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStrip1.Opening
        Try
            If lstBackdrops.Items.Count = 0 Then
                e.Cancel = True
            ElseIf lstBackdrops.SelectedItems.Count <> 1 Then
                e.Cancel = True

            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub mnuFanArt2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuFanArt2.Click
        Try
            If mnuFanArt2.Checked = False Then
                lstBackdrops.SelectedItems(0).BackColor = Color.Red
                mnuFanArt2.Checked = True
                Dim s As KeyValuePair(Of Bitmap, String) = lstBackdrops.SelectedItems(0).Tag
                bmpFanArt2 = New Bitmap(s.Key)
            ElseIf lstBackdrops.SelectedItems(0).BackColor = Color.Red Then
                mnuFanArt2.Checked = False
                lstBackdrops.SelectedItems(0).BackColor = Color.White
            Else
                For Each lvi As ListViewItem In lstBackdrops.Items
                    If lvi.BackColor = Color.Red Then
                        lvi.BackColor = Color.White
                    End If
                Next
                lstBackdrops.SelectedItems(0).BackColor = Color.Red
                Dim s As KeyValuePair(Of Bitmap, String) = lstBackdrops.SelectedItems(0).Tag
                bmpFanArt2 = New Bitmap(s.Key)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub mnuFanArt3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuFanArt3.Click
        Try
            If mnuFanArt3.Checked = False Then
                lstBackdrops.SelectedItems(0).BackColor = Color.Green
                mnuFanArt3.Checked = True
                Dim s As KeyValuePair(Of Bitmap, String) = lstBackdrops.SelectedItems(0).Tag
                bmpFanArt3 = New Bitmap(s.Key)
            ElseIf lstBackdrops.SelectedItems(0).BackColor = Color.Green Then
                mnuFanArt3.Checked = False
                lstBackdrops.SelectedItems(0).BackColor = Color.White
            Else

                For Each lvi As ListViewItem In lstBackdrops.Items
                    If lvi.BackColor = Color.Green Then
                        lvi.BackColor = Color.White
                    End If
                Next
                lstBackdrops.SelectedItems(0).BackColor = Color.Green
                Dim s As KeyValuePair(Of Bitmap, String) = lstBackdrops.SelectedItems(0).Tag
                bmpFanArt3 = New Bitmap(s.Key)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub btnClearFanArt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearFanArt.Click
        clearFanArt()
        For Each lvi As ListViewItem In lstBackdrops.Items
            lvi.BackColor = Color.White
        Next
    End Sub

    Private Sub txtDVDIcon_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDVDIcon.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtDVDIcon.Text = OpenFileDialog1.FileName
            My.Settings.DVDPath = txtDVDIcon.Text
        End If
    End Sub

    Private Sub txtXvidIcon_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtXvidIcon.Enter
        OpenFileDialog1 = New OpenFileDialog
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtXvidIcon.Text = OpenFileDialog1.FileName
            My.Settings.XvidPath = txtXvidIcon.Text
        End If
    End Sub

    Private Sub txtDivxIcon_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDivxIcon.Enter
        OpenFileDialog1 = New OpenFileDialog
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtDivxIcon.Text = OpenFileDialog1.FileName
            My.Settings.DvixPath = txtDivxIcon.Text
        End If
    End Sub

    Private Sub TabControl1_TabIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        If TabControl1.SelectedIndex <> 0 And btnGenerate.Visible = False Then
            'pnlMovieInfo.Visible = False
            'btnEditMovieInfo.Text = "EDIT"
            'pbExistingSheet.Size = New Size(960, 540)
            pbExistingSheet.Size = New Size(640, 360)
            'PictureBox1.Image = loadedBitmap
            PictureBox1.Size = New Size(1010, 568)
            PictureBox1.Location = New Point(0, 40)
            'btnEditInfo.Text = "Edit Movie Info"
        End If
    End Sub

    Private Sub lstTemplates_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstTemplates.SelectedIndexChanged
        Try
            Dim newBmp As Bitmap
            Dim sTemplateLocation As String = ""
            If lstTemplates.SelectedIndices.Count > 0 Then
                sTemplateLocation = lstTemplates.Items(lstTemplates.SelectedIndices(0)).SubItems(1).Text.Replace("*", "")
                sTemplateLocation = sTemplateLocation.Replace("Template.xml", "")
                sTemplateLocation = sTemplateLocation & "wdtv_preview.jpg"
                If IO.File.Exists(sTemplateLocation) Then
                    newBmp = New Bitmap(sTemplateLocation)
                    pbPreview.Image = newBmp
                    Application.DoEvents()
                Else
                    pbPreview.Image = Nothing
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub TxtDolbyStereo_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles TxtDolbyStereo.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            TxtDolbyStereo.Text = OpenFileDialog1.FileName
            My.Settings.DolbyStereoPath = TxtDolbyStereo.Text
        End If
    End Sub

    Private Sub txtMPEGaudio_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtMPEGaudio.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtMPEGaudio.Text = OpenFileDialog1.FileName
            My.Settings.MPEGAudioPath = txtMPEGaudio.Text
        End If
    End Sub

    Private Sub txtMPEGvideo_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtMPEGvideo.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtMPEGvideo.Text = OpenFileDialog1.FileName
            My.Settings.MPEGvideoPath = txtMPEGvideo.Text
        End If
    End Sub

    Private Sub btnExit_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        Application.Exit()
    End Sub

    Private Sub ToolTip1_Popup(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PopupEventArgs) Handles ToolTip1.Popup

    End Sub

    Private Sub txtMKVIcon_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMKVIcon.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtMKVIcon.Text = OpenFileDialog1.FileName
            My.Settings.MKVPath = txtMKVIcon.Text
        End If
    End Sub

    Private Sub txtH264Icon_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtH264Icon.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtH264Icon.Text = OpenFileDialog1.FileName
            My.Settings.H264Path = txtH264Icon.Text
        End If
    End Sub

    Private Sub cbManuallyInput_AppearanceChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbManuallyInput.AppearanceChanged

    End Sub

    Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbManuallyInput.CheckedChanged
        If cbManuallyInput.Checked = True Then
            gbStreams.Enabled = True
        Else
            cmbVIDEOStream.Text = ""
            cmbAudioStream1.Text = ""
            cmbAudioStream2.Text = ""
            cmbFiletype.Text = ""
            gbStreams.Enabled = False
        End If
    End Sub

    Private Sub btnIncorrectFilm_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub btnGo_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click
        Try
            txtStatus.Clear()

            pbExistingSheet.Visible = False
            pnlCreateSheet.Visible = True

            'btnMoreFound.Visible = False

            LogManual("Override Used, searching for " & txtOverride.Text, 1)
            If My.Settings.PrimarySource = "MovieDB" Then
                Dim movieID = SearchOnTMDb_manual(txtOverride.Text)
                LogManual("Movie Found ID:" & movieID.ToString, 1)
                populateBackdrops(movieID)
                populatePosters()
                populateMovieInfo()
                txtOverride.Text = ""
            Else
                SearchOnIMDb(txtOverride.Text, 0)
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

        btnGenerate.Visible = True

    End Sub


    Private Sub txtSummary_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSummary.TextChanged
        If txtSummary.Text.Length >= 550 Then
            lbWarning.Text = " - There are " & txtSummary.Text.Length.ToString & " characters. It may exceed the space on the template."
        Else
            lbWarning.Text = ""
        End If
    End Sub

    Private Sub txtISOIcon_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtISOIcon.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtISOIcon.Text = OpenFileDialog1.FileName
            My.Settings.ISOPath = txtISOIcon.Text
        End If
    End Sub
    Private Sub AnalyseMovie(ByVal movie)
        'get MKV file name
        Dim direcInfo As New IO.DirectoryInfo(movie.Key)
        Dim targetFile As String = ""
        Dim fileAry As New List(Of IO.FileInfo)
        fileAry.AddRange(direcInfo.GetFiles("*.mkv"))
        'fileAry.AddRange(direcInfo.GetFiles("*.iso"))
        fileAry.AddRange(direcInfo.GetFiles("*.avi"))
        fileAry.AddRange(direcInfo.GetFiles("*.wmv"))
        fileAry.AddRange(direcInfo.GetFiles("*.vob"))
        fileAry.AddRange(direcInfo.GetFiles("*.divx"))
        fileAry.AddRange(direcInfo.GetFiles("*.m2ts"))
        fileAry.AddRange(direcInfo.GetFiles("vts_01_0.ifo"))
        fileAry.AddRange(direcInfo.GetFiles("*.mp4"))
        Dim maxSize As Long = 0
        For Each f In fileAry
            If f.Length > maxSize Then
                targetFile = f.FullName
            End If
        Next
        If targetFile <> vbNullString Then
            getVideoInfo(targetFile)
        End If
    End Sub

    Private Sub txtAACIcon_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAACIcon.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtAACIcon.Text = OpenFileDialog1.FileName
            My.Settings.AACPath = txtAACIcon.Text
        End If
    End Sub

    Private Sub txtBlueRayIcon_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBlueRayIcon.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtBlueRayIcon.Text = OpenFileDialog1.FileName
            My.Settings.BluRayPath = txtBlueRayIcon.Text
        End If
    End Sub


    Private Sub TxtAAC51icon_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TxtAAC51icon.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            TxtAAC51icon.Text = OpenFileDialog1.FileName
            My.Settings.AAC51Path = TxtAAC51icon.Text
        End If

    End Sub


    Private Sub TxtFLACicon_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TxtFLACicon.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            TxtFLACicon.Text = OpenFileDialog1.FileName
            My.Settings.FLACPath = TxtFLACicon.Text
        End If

    End Sub

    Private Sub txtVorbisIcon_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtVorbisIcon.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtVorbisIcon.Text = OpenFileDialog1.FileName
            My.Settings.VorbisPath = txtVorbisIcon.Text
        End If
    End Sub
    Private Function getLanguageCode()
        Dim language As String
        Select Case My.Settings.Language
            Case 0
                language = "en" 'English
            Case 1
                language = "de" 'German
            Case 2
                language = "ru" 'Russian
            Case 3
                language = "nl" 'Dutch
            Case 4
                language = "fr" 'French
            Case 5
                language = "es" 'Spanish
            Case 6
                language = "pt" 'Portugese
            Case 7
                language = "it" 'Italian
            Case Else
                language = "en"
        End Select
        Return language

    End Function
    Private Sub btnSaveSetting2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveSetting2.Click
        Try
            If DefaultWDTV.Checked = True Then
                My.Settings.DefaultWDTV = True
                My.Settings.Msheet_t_b_s = False
                My.Settings.Showcase = False
            ElseIf Msheet_T_b_s.Checked = True Then
                My.Settings.Msheet_t_b_s = True
                My.Settings.Showcase = False
                My.Settings.DefaultWDTV = False
            ElseIf chkShowcase.Checked = True Then
                My.Settings.Showcase = True
                My.Settings.DefaultWDTV = False
                My.Settings.Msheet_t_b_s = False
            End If
            My.Settings.Save()
            MsgBox("Settings Successfully Saved", vbOKOnly, "Save Settings")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
End Class

